定义Student类和Score类,输出一个学生的成绩单(包括学号、姓名、高等数学、英语成绩)。要求通过以下三种方法实现: 方法1:非成员函数作为友元函数 方法2:成员函数作为友元函数 方法3:友元类
时间: 2024-03-25 08:36:50 浏览: 89
好的,我来回答你的问题。
首先,我们先定义一个Student类和一个Score类。其中,Student类包含学号和姓名两个成员变量,Score类包含高等数学和英语两个成员变量。代码如下:
```c++
class Score {
private:
int math;
int english;
public:
Score(int m, int e) {
math = m;
english = e;
}
friend class Student;
friend void printScore(Student s);
};
class Student {
private:
int id;
string name;
Score score;
public:
Student(int i, string n, int m, int e) : id(i), name(n), score(m, e) {}
friend void printScore(Student s);
friend void printScore2(Student s);
friend class Score;
};
```
接下来,我们需要输出一个学生的成绩单,包括学号、姓名、高等数学、英语成绩。我们可以通过以下三种方法实现:
方法1:非成员函数作为友元函数
```c++
void printScore(Student s) {
cout << "学号:" << s.id << endl;
cout << "姓名:" << s.name << endl;
cout << "高等数学成绩:" << s.score.math << endl;
cout << "英语成绩:" << s.score.english << endl;
}
```
方法2:成员函数作为友元函数
```c++
void Student::printScore2() {
cout << "学号:" << id << endl;
cout << "姓名:" << name << endl;
cout << "高等数学成绩:" << score.math << endl;
cout << "英语成绩:" << score.english << endl;
}
```
方法3:友元类
```c++
void Score::printScore(Student s) {
cout << "学号:" << s.id << endl;
cout << "姓名:" << s.name << endl;
cout << "高等数学成绩:" << math << endl;
cout << "英语成绩:" << english << endl;
}
```
最后,我们可以创建一个学生对象,并调用以上三个方法来输出他的成绩单:
```c++
int main() {
Student s(1001, "Tom", 90, 80);
printScore(s); // 方法1
s.printScore2(); // 方法2
Score::printScore(s); // 方法3
return 0;
}
```
输出结果如下:
```
学号:1001
姓名:Tom
高等数学成绩:90
英语成绩:80
学号:1001
姓名:Tom
高等数学成绩:90
英语成绩:80
学号:1001
姓名:Tom
高等数学成绩:90
英语成绩:80
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)