我有一个名为 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();
};
在另一个类(class),我有这个方法:
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
在print方法中的2个people[i]下面有红线
我做错了什么?
最佳答案
getName
不是 const,getScore
不是 const,但 print
是。将前两个 const 设为 print
。您不能使用 const 对象调用非常量方法。由于您的 Person 对象是其他类的直接成员,并且由于您在 const 方法中,因此它们被视为 const。
一般来说,你应该考虑你编写的每一个方法,如果是这样的话,就将它声明为 const。 getScore
和 getName
等简单的 getter 应始终为 const。
关于c++ - 智能感知 : the object has type qualifiers that are not compatible with the member function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13103755/