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

IntelliSense: the object has type qualifiers that are not compatible with the member function

本文关键字:不兼容 类型 函数 成员 对象 IntelliSense      更新时间:2023-10-16

我有一个叫人的类:

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像print。您不能用const对象调用非const方法。由于您的个人对象是您的其他班级的直接成员,并且由于您使用的是const方法,因此被认为是const。

通常,您应该考虑您编写的每种方法并将其声明为const。诸如getScoregetName之类的简单获取器应始终为const。

相关文章: