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

标签 c++ visual-studio-2010

我有一个名为 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/

相关文章:

c++ - opencv 中的视觉里程计(可能使用 RGBD)

c++ - 获取 Cimg 库中渲染文本的尺寸

c - 将巨大的数据库加载到内存中 visual c

c# - .net 应用程序更新

visual-studio - VS中平台和平台目标的区别

c - 如何将 POSIX 系统调用 fork() 和 wait() 移植到 Visual Studio 2010 Express?

c++ - 底层 STL:在没有新 vector 的情况下将 std::vector 连接到自身

c++ - QT 创建我的表单对象,如何访问该表单?

C++ 无法将 'type' 转换为 'type*'

.net - 如何创建类库的版本以支持 .NET Framework 的多个版本?