IntelliSense:对象具有与成员函数不兼容的类型限定符

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.

  • 在你的其他课堂上(我推测)`人们[尺寸];`.这意味着在你的另一个类的`const`方法中你不能改变`people`数组,所以例如`people [0] = x;`将是非法的.调用非常量`Person`方法只是改变`people`数组的另一种方式,所以`people [0] .setScore(20.0);`也是非法的.因为您没有将`Person :: getScore()`声明为const,编译器不知道您没有尝试更改`people`数组,所以它给出了一个错误. (2认同)