我有一个类叫做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();
};
在另一个类中,我有这个方法:
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;
}
这是人的宣言:
static const int size=8;
Person people[size];
当我尝试编译它,我得到这个错误:
IntelliSense: the object has type qualifiers that are not compatible with the member function
在2人[i]的打印方式下的红线
我究竟做错了什么?
解决方法
getName不是const,getscore不是const,而是print.使第一个两个const像打印.您不能使用const对象调用非const方法.因为你的Person对象是你的另一个类的直接成员,并且由于你是一个const方法,所以它们被认为是const.
一般来说,你应该考虑你写的每个方法,并声明它是const,如果这是它是什么. getscore和getName等简单的getter应该是const.