这篇文章介绍c++如何对运算符进行重载,我们通过一个小练习题来认识
要求:对输入的学生数据来进行排序,成绩按照从大到小的顺序排列,如果成绩相同,则按照学号大小进行从小到大排列
代码如下:需要注意的是我们涉及到大小比较的时候一般情况下重载小于号
#include<iostream>
#include<algorithm>
using namespace std;
class student{
public:
int code,//学号
achie;//成绩
//重载小于号
bool operator<(const student &stu){
if(this->achie == stu.achie) return this->code < stu.code;
return this->achie > stu.achie;
}
};
int main(){
int number;//多少个学生
student num[100];
cin >> number;
for(int i = 0;i<number;i++){
cin >> num[i].code >> num[i].achie;
}
sort(num,num+number);
for(int y = 0;y<number;y++){
cout << num[y].code << " " << num[y].achie << endl;
}
return 0;
}