微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 智能感知:对象具有与成员函数不兼容的类型限定符

我有一个类叫做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像打印.您不能使用const对象调用非const方法.因为你的Person对象是你的另一个类的直接成员,并且由于你是一个const方法,所以它们被认为是const.

一般来说,你应该考虑你写的每个方法,并声明它是const,如果这是它是什么. getscore和getName等简单的getter应该是const.

原文地址:https://www.jb51.cc/c/116019.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐