#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Student {
private:
string name;
int score;
public:
Student(string n, int s) : name(n), score(s) {}
int getScore() const {
return score;
}
string getName() const {
return name;
}
};
// 比较函数,用于按成绩从高到低排序
bool compareByScore(const Student& a, const Student& b) {
return a.getScore() > b.getScore();
}
// 排序函数
void sortStudentsByScore(Student* students, int size) {
std::sort(students, students + size, compareByScore);
}
int main() {
Student students[] = {Student("Alice", 85), Student("Bob", 90), Student("Charlie", 78)};
int size = sizeof(students) / sizeof(students[0]);
sortStudentsByScore(students, size);
for (int i = 0; i < size; ++i) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
return 0;
}
用到的C++对象特征说明
- 封装:在
Student
类中,将成员变量name
和score
声明为private
,通过公有的成员函数getScore
和getName
来访问,实现了数据的封装,保证数据的安全性和一致性。
- 函数重载:这里虽然没有直接体现函数重载,但
std::sort
函数是一个重载函数,它有多个版本,根据我们传递的比较函数compareByScore
来进行特定方式的排序。
- 多态:通过传递不同的比较函数(函数对象)给
std::sort
,实现了不同的排序逻辑,这体现了函数对象的多态性。在这个例子中,compareByScore
函数就是一个具体的比较逻辑实现,体现了行为的多态性。