为什么 const 不起作用

Why const does not work

class Student{
public:
    Student();
    Student(string name, int score);
    string getName();
    int getScore();
    void insert(string name, int score);
    friend ostream& operator<<(ostream& os, const Student& student){
        os << "Name: "<<student.name<<",Score:"<<student.score<<endl;
        return os;
    }
 private:
    string name;
    int score;

};


string Student::getName(){
    return name;
}
int Student::getScore(){
    return score;
}

我在上面定义class

和main函数我定义了一个比较函数

int compStudent(const Student &student1, const Student &student2){
    int score1 = student1.getScore();
    int score2 = student2.getScore();
    if(score1 == score2) return 0;
    if(score1<score2) return -1;
    return 1;
}

然后报错说this argument is const but function is not const

然后我删除了const,为什么有效?

为了能够在 const 对象上调用 getScore(),需要声明该方法 const:

class Student{
    ...
    int getScore() const;
    ...
};


int Student::getScore() const {
    return score;
}

请参阅 Meaning of "const" last in a C++ method declaration? 进行讨论。

int score1 = student1.getScore();

调用 student1 的 getScore() 方法,这是一个常量引用。但是getScore()方法不是const方法(不保证不修改student1)。

要解决此问题,请修改方法以表明它是常量:

class Student {
    // ...
    int getScore() const;
    // ...
};