use*_*366 -3 c++ const reference
class Counter {
int count;
void setCount()
{
this->count=10;
}
//declaration
friend const Counter& operator+=( Counter &a, Counter &b);
}
//definition
const Counter& operator+=(Counter &a, Counter &b) {
a.count = a.count + b.count;
return a;//returning reference to object a with const which makes object //pointed by ref. a read only in calling function
}
main() {
Counter c1,c2;
(c1+=c2);
c1.setCount();
}
Run Code Online (Sandbox Code Playgroud)
main()第2行:调用opearator + =函数并获取对只读对象的引用,因为它返回const Counter&
我的问题是,在main()第3行中:为什么现在允许我更改c1的状态/属性?我确实在+ =运算符中将其作为const引用返回。请解释
仅仅因为您的operator + =返回了对Counter的const引用,它并没有成为c1const Counter。
如果尝试这样做(c1+=c2).setCount(),那将失败,因为它将尝试在const引用上调用non-const setCount方法,该引用c1由operator + =返回
旁注:operator + =的第二个参数可能应该是const引用...