一段代码:
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 的。
网友评论