I have a class called 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
What am I doing wrong?
getNameis not const,getScoreis not const, butprintis. Make the first two const likeprint. 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.In general you should consider every method you write and declare it const if that’s what it is. Simple getters like
getScoreandgetNameshould always be const.