【发布时间】:2015-12-28 03:00:12
【问题描述】:
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();
}
main() 第 2 行:调用 operator+= 函数并获取对只读对象的引用,因为它返回 const Counter&
我的问题是, 在 main() 第 3 行:为什么我现在可以更改 c1 的状态/属性?我确实在 += 运算符中将它作为 const 引用返回。请解释一下
【问题讨论】: