C++ IntelliSense:对象具有与成员函数不兼容的类型限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13103755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IntelliSense: the object has type qualifiers that are not compatible with the member function
提问by Chin
I have a class called Person:
我有一个名为 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();
};
In another class, I have this method:
在另一堂课中,我有这个方法:
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;
}
This is the declaration of people:
这是人们的宣言:
static const int size=8;
Person people[size];
When I try to compile it I get this error:
当我尝试编译它时,出现此错误:
IntelliSense: the object has type qualifiers that are not compatible with the member function
with red lines under the the 2 people[i]in the print method
打印方法中2 people[i]下方有红线
What am I doing wrong?
我究竟做错了什么?
回答by john
getName
is not const, getScore
is not const, but print
is. Make the first two const like print
. You cannot call a non-const method with a const object. Since your Person objects are direct members of your other class and since you are in a const method they are considered const.
getName
不是常量,getScore
不是常量,而是print
。使前两个 const 像print
. 您不能使用 const 对象调用非常量方法。由于您的 Person 对象是您的其他类的直接成员,并且由于您使用的是 const 方法,因此它们被视为 const。
In general you should consider every method you write and declare it const if that's what it is. Simple getters like getScore
and getName
should always be const.
一般而言,您应该考虑您编写的每个方法,并声明它为 const(如果确实如此)。简单的 getter 喜欢getScore
并且getName
应该始终是 const。