Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么const不起作用 班级学生{ 公众: 学生(); 学生(字符串名称,整数分数); 字符串getName(); int getScore(); 无效插入(字符串名称、整数分数); friend ostream&operator_C++_Constants - Fatal编程技术网

C++ 为什么const不起作用 班级学生{ 公众: 学生(); 学生(字符串名称,整数分数); 字符串getName(); int getScore(); 无效插入(字符串名称、整数分数); friend ostream&operator

C++ 为什么const不起作用 班级学生{ 公众: 学生(); 学生(字符串名称,整数分数); 字符串getName(); int getScore(); 无效插入(字符串名称、整数分数); friend ostream&operator,c++,constants,C++,Constants,要能够对const对象调用getScore(),需要声明const方法: int compStudent(const Student &student1, const Student &student2){ int score1 = student1.getScore(); int score2 = student2.getScore(); if(score1 == score2) return 0; if(score1<score2) re

要能够对
const
对象调用
getScore()
,需要声明
const
方法:

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;
}
有关讨论,请参阅。

该行

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


int Student::getScore() const {
    return score;
}
调用student1上的
getScore()
方法,该方法是常量引用。但是
getScore()
方法不是常量方法(它不承诺不修改
student1

要解决此问题,请修改该方法以指示其为常量:

int score1 = student1.getScore();

谢谢你的回复!
int score1 = student1.getScore();
class Student {
    // ...
    int getScore() const;
    // ...
};