美文网首页
passing 'xxx' as 'th

passing 'xxx' as 'th

作者: 顽强的猫尾草 | 来源:发表于2018-10-14 18:13 被阅读7次

一段代码:

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 的。

相关文章

网友评论

      本文标题:passing 'xxx' as 'th

      本文链接:https://www.haomeiwen.com/subject/alktzftx.html