Chi*_*hin 21 c++ visual-studio-2010
我有一个名为Person的类:
class Person {
string name;
long score;
public:
Person(string name="", long score=0);
void setName(string name);
void setScore(long score);
string getName();
long getScore();
};
Run Code Online (Sandbox Code Playgroud)
在另一个类中,我有这个方法:
void print() const {
for (int i=0; i< nPlayers; i++)
cout << "#" << i << ": " << people[i].getScore()//people is an array of person objects
<< " " << people[i].getName() << endl;
}
Run Code Online (Sandbox Code Playgroud)
这是人们的宣言:
static const int size=8;
Person people[size];
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我收到此错误:
IntelliSense: the object has type qualifiers that are not compatible with the member function
Run Code Online (Sandbox Code Playgroud)
打印方法中2 人[i]下的红线
我究竟做错了什么?
joh*_*ohn 28
getName不是常量,getScore不是常量,而是print.让前两个const像print.您不能使用const对象调用非const方法.由于您的Person对象是您的其他类的直接成员,并且由于您使用的是const方法,因此它们被视为const.
一般来说,你应该考虑你编写的每个方法,并将其声明为const,如果它是什么.简单的getter喜欢getScore并且getName应该总是const.
| 归档时间: |
|
| 查看次数: |
45315 次 |
| 最近记录: |