学生类Student成员:id,yw,sx,sum,定于5位学生对象,对学生对象降序排序,编写“<”运算符函数,用于比较两个对象的大小
时间: 2023-08-16 07:08:04 浏览: 47
以下是实现上述需求的示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Student {
public:
int id; // 学号
int yw; // 语文成绩
int sx; // 数学成绩
int sum; // 总成绩
// 构造函数
Student(int id, int yw, int sx) {
this->id = id;
this->yw = yw;
this->sx = sx;
this->sum = yw + sx;
}
// < 运算符函数
bool operator<(const Student& other) const {
return sum > other.sum;
}
};
int main() {
Student s1(1001, 80, 90);
Student s2(1002, 85, 95);
Student s3(1003, 90, 85);
Student s4(1004, 95, 90);
Student s5(1005, 85, 80);
Student students[] = {s1, s2, s3, s4, s5};
sort(students, students + 5);
for (int i = 0; i < 5; i++) {
cout << "学号:" << students[i].id << ",总成绩:" << students[i].sum << endl;
}
return 0;
}
```
运行结果为:
```
学号:1004,总成绩:185
学号:1002,总成绩:180
学号:1003,总成绩:175
学号:1001,总成绩:170
学号:1005,总成绩:165
```
在上述代码中,定义了一个名为 Student 的类,该类包含 4 个成员变量,分别是学号(id)、语文成绩(yw)、数学成绩(sx)和总成绩(sum)。在构造函数中,会根据语文成绩和数学成绩计算总成绩。
为了实现对学生对象的降序排序,我们在类中重载了 `<` 运算符函数,该函数比较两个学生对象的总成绩大小,如果第一个学生对象的总成绩大于第二个学生对象的总成绩,则返回 true,否则返回 false。
在主函数中,我们定义了 5 个学生对象,并将它们存储在一个数组中。然后使用 `sort` 函数对该数组进行排序,由于我们已经在类中重载了 `<` 运算符函数,所以 `sort` 函数会自动调用该函数进行比较。
最后,我们遍历排序后的数组,并输出每个学生对象的学号和总成绩。