簡體   English   中英

IntelliSense:對象具有與成員函數不兼容的類型限定符

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

我有一個名為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();
};

在另一個類中,我有這個方法:

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方法。 由於您的Person對象是您的其他類的直接成員,並且由於您使用的是const方法,因此它們被視為const。

一般來說,你應該考慮你編寫的每個方法,並將其聲明為const,如果它是什么。 getScoregetName這樣的簡單getter應該始終是const。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM