简体   繁体   English

为什么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;
}

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. 然后错误说这个参数是const但函数不是const。

Then I delete the const, it works why? 然后我删除了const,它为什么起作用?

To be able to call getScore() on a const object, the method needs to be declared const : 为了能够在const对象上调用getScore() ,需要将该方法声明为const

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


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

See Meaning of "const" last in a C++ method declaration? 在C ++方法声明中最后看到“ const”的含义吗? for a discussion. 进行讨论。

The line 线

int score1 = student1.getScore();

calls the getScore() method on student1, which is a const reference. getScore()上调用getScore()方法,该方法是一个const引用。 But the getScore() method is not a const method (it doesn't promise not to modify student1 ). 但是getScore()方法不是const方法(它不能保证不修改student1 )。

To fix this, modify the method to indicate it is const: 要解决此问题,请修改方法以指示它为const:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM