有一个学生类Student,包括学生姓名和成绩,设计一个友元函数,比较学生成绩的高低,并输出高分和低分的学生姓名
时间: 2024-10-24 12:10:22 浏览: 55
在C++中,你可以设计一个`Student`类,然后声明一个友元函数(Friend Function),它允许这个函数访问类的私有成员。首先,我们需要定义一个`Student`类,包含姓名和成绩:
```cpp
class Student {
private:
string name;
int score;
public:
// 构造函数、getter和setter等
Student(string name, int score) : name(name), score(score) {}
friend void compare_scores(Student studentList[], int size);
};
```
接下来,我们可以定义友元函数`compare_scores`,它接受一个学生数组和数组长度,通过遍历数组找出最高分和最低分的学生:
```cpp
void compare_scores(Student studentList[], int size) {
if (size <= 1) {
cout << "无法比较,学生列表过少。\n";
return;
}
int maxScore = studentList[0].score;
int minScore = studentList[0].score;
string highScoreName, lowScoreName;
for (int i = 1; i < size; i++) {
if (studentList[i].score > maxScore) {
maxScore = studentList[i].score;
highScoreName = studentList[i].name;
}
if (studentList[i].score < minScore) {
minScore = studentList[i].score;
lowScoreName = studentList[i].name;
}
}
cout << "高分学生姓名:" << highScoreName << ", 分数:" << maxScore << endl;
cout << "低分学生姓名:" << lowScoreName << ", 分数:" << minScore << endl;
}
```
阅读全文