MST

星途 面试题库

面试题:C++对象特征在数据排序中的应用

在C++中,假设有一个包含学生成绩的类Student,成员变量有姓名(string类型)和成绩(int类型)。请利用C++的对象特征,实现一个函数,能够对一个Student对象数组按成绩从高到低进行排序,并简要说明用到了C++哪些对象特征。
43.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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++对象特征说明

  1. 封装:在Student类中,将成员变量namescore声明为private,通过公有的成员函数getScoregetName来访问,实现了数据的封装,保证数据的安全性和一致性。
  2. 函数重载:这里虽然没有直接体现函数重载,但std::sort函数是一个重载函数,它有多个版本,根据我们传递的比较函数compareByScore来进行特定方式的排序。
  3. 多态:通过传递不同的比较函数(函数对象)给std::sort,实现了不同的排序逻辑,这体现了函数对象的多态性。在这个例子中,compareByScore函数就是一个具体的比较逻辑实现,体现了行为的多态性。