gpt4 book ai didi

c++ - 智能感知 : the object has type qualifiers that are not compatible with the member function

转载 作者:IT老高 更新时间:2023-10-28 22:02:52 33 4
gpt4 key购买 nike

我有一个名为 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。 getScoregetName 等简单的 getter 应始终为 const。

关于c++ - 智能感知 : the object has type qualifiers that are not compatible with the member function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13103755/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com