有一个学生类,包括学生姓名、某科成绩,设计一个友元函数,比较学生成绩的高低,并求出一组学生中最高分和最低分。(可定义对象数组或定义三个以上对象)
时间: 2024-12-16 09:25:48 浏览: 40
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
double score;
public:
Student(string n, double s) : name(n), score(s) {}
// 获取学生信息
string getName() const { return name; }
double getScore() const { return score; }
// 友元函数,比较成绩并找出最高分和最低分
friend void compareScores(const Student* students, int size);
};
// 友元函数实现
void compareScores(const Student* students, int size) {
double max_score = students[0].getScore();
double min_score = students[0].getScore();
string max_name, min_name;
for (int i = 1; i < size; ++i) {
if (students[i].getScore() > max_score) {
max_score = students[i].getScore();
max_name = students[i].getName();
}
if (students[i].getScore() < min_score) {
min_score = students[i].getScore();
min_name = students[i].getName();
}
}
cout << "最高分学生: " << max_name << " 分数: " << max_score << endl;
cout << "最低分学生: " << min_name << " 分数: " << min_score << endl;
}
int main() {
// 创建学生对象数组
Student students[] = {
{"Alice", 90},
{"Bob", 85},
{"Charlie", 95},
{"David", 88}
};
int num_students = sizeof(students) / sizeof(students[0]);
compareScores(students, num_students);
return 0;
}
```
这个程序定义了一个`Student`类,包含姓名和成绩属性,并提供了一个获取名字和成绩的公有方法。`compareScores`是一个友元函数,它接受一个指向学生对象的指针数组和数组长度,遍历数组比较每个学生的成绩,找到最高分和最低分的学生及其分数。在`main`函数中,我们创建了一个学生对象数组,并调用了`compareScores`函数来找出最高分和最低分。
阅读全文
相关推荐


















