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