-1
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;
}

I define above class

and main function I define a comparison function

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;
}

Then the error is said this argument is const but function is not const.

Then I delete the const, it works why?

大王花
  • 51
  • 1
  • 1
  • 6

2 Answers2

3

To be able to call getScore() on a const object, the method needs to be declared const:

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


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

See Meaning of "const" last in a C++ method declaration? for a discussion.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

The line

int score1 = student1.getScore();

calls the getScore() method on student1, which is a const reference. But the getScore() method is not a const method (it doesn't promise not to modify student1).

To fix this, modify the method to indicate it is const:

class Student {
    // ...
    int getScore() const;
    // ...
};
halfflat
  • 1,584
  • 8
  • 11