加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将’const’作为’this’参数传递错误

发布时间:2020-12-16 10:25:38 所属栏目:百科 来源:网络整理
导读:我很久以来就遇到了错误,接下来,我正在学习,我想我不明白这个错误. droid.cpp: In function ‘std::ostream operator(std::ostream,const Droid)’: droid.cpp:94:30: error: passing ‘const Droid’ as ‘this’ argument of ‘std::string Droid::getId()
我很久以来就遇到了错误,接下来,我正在学习,我想我不明白这个错误.

droid.cpp: In function ‘std::ostream& operator<<(std::ostream&,const Droid&)’: 

droid.cpp:94:30: error: passing ‘const Droid’ as ‘this’ argument of ‘std::string 

Droid::getId()’ discards qualifiers
 [-fpermissive]

第94行:

std::ostream&   operator<<(std::ostream &os,Droid const & a)
    os << "Droid '" << a.getId() << "'," << *a.getStatus() << "," << a.getEnergy() << std::endl;

和听众:

std::string   getId();

我对“operator<<”,a.getId,a.getStatus,a.getEnergy中的3个调用有相同的错误. 有人可以向我解释一下编译器在说什么吗?

解决方法

您需要将该方法设为const,以便可以在const实例上或通过const引用调用它:

std::string   getId() const;
                      ^^^^^

这同样适用于在std :: ostream& amp;中调用的所有Droid方法. operator<<(std :: ostream& os,Droid const& a). 您还需要在方法的定义中添加const.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读