passing 'xxx' as 'this' argument discards qualifiers

一段代码:

bool BigNum::operator==(const int& n) {
    ...
}

BigNum BigNum::operator/(const BigNum& n) {
    if (n == 0) { ... }
    ...
}

报错:

error: no match for ‘operator==’ (operand types are ‘const BigNum’ and ‘int’)
     if (n == 0) {
           ^
bigNum.cpp:102:6: note: candidate: bool BigNum::operator==(const int&) <near match>
 bool BigNum::operator==(const int& n) {
      ^
bigNum.cpp:102:6: note:   passing ‘const BigNum*’ as ‘this’ argument discards qualifiers

错误点在于 n 是用 const 修饰的,他只能调用 const 函数。尽管那个函数并不会修改 n 的值。

因此需要修改成:

bool BigNum::operator==(const int& n) const {
    ...
}

注意函数的 const 是写在最后,如果写在 bool 前表示的是返回值为 const 的。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,914评论 1 32
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,089评论 8 265
  • 水墨牡丹(自己尝试的新风格(⊙o⊙)哦) 原稿是工笔白描在宣纸上画的,还用红和粉做了渲染。 而我是在速写本上画的...
    吾栖梦阅读 3,701评论 0 1
  • 周六上午,姐姐打电话让回家吃饭。说有两个目的,其一是回去陪爸妈过个老人节,其二是提前为我过生日。我回复她:...
    静观微澜阅读 2,593评论 1 2

友情链接更多精彩内容