【发布时间】:2020-04-02 22:11:55
【问题描述】:
谁能解释一下这个错误? 代码如下:
class O{
unsigned x;
unsigned y;
public:
O(unsigned x_ ,unsigned y_): x(x_), y(y_){
};
O& operator+= ( O & object){
x += object.x;
}
};
class A {
O item;
public:
A(O i): item(i){;
}
void fun() const{
O j(2,3);
j += item;
}
};
int main(){
return 0;
}
当我尝试编译时出现此错误:
In member function 'void A::fun() const':
[Error] no match for 'operator+=' (operand types are 'O' and 'const O')
[Note] candidate is:
[Note] O& O::operator+=(O&)
[Note] no known conversion for argument 1 from 'const O' to 'O&'
谁能解释一下?如果我将 const 限定符添加到 += 运算符的参数,它会编译。所以我认为问题在于我在 const 函数 fun() 内将 item 的引用传递给 += 运算符,它是非 const。谁能解释我为什么这是非法的,以及我如何避免犯这种错误,例如在使用 const 限定符等时有一些经验法则可以遵循?
【问题讨论】:
-
在 const 限定函数 (
void fun() const) 内部,每个类字段都被视为const。非 const 引用不能绑定到 const 事物。 -
在 const 方法中调用
j += item会使item成为常量,因此需要实现采用const引用的运算符。
标签: c++ class reference constants const-reference