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人[i]下的红线
What am I doing wrong?
我究竟做错了什么?
1 个解决方案
#1
22
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不是const,getScore不是const,而是print。使前两个const像print一样。您不能使用const对象调用非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,如果它是这样的话。像getScore和getName这样的简单getter应该始终是const。
#1
22
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不是const,getScore不是const,而是print。使前两个const像print一样。您不能使用const对象调用非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,如果它是这样的话。像getScore和getName这样的简单getter应该始终是const。