[英]Why do we have to return by reference when overloading += operator
While overloading += operator why do we have to return by reference. 在重载+ =运算符时,为什么我们必须通过引用返回。 for eg the below code also do the same thing
例如,下面的代码也做同样的事情
class Integer
{
int i;
public:
Integer::Integer(int i):i(i){}
void operator+=(const Integer& arg)
{
i = i + arg.i;
}
};
//main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
Integer a(10),b(20);
b += a;
}
Most of the books suggest that for the above operator overloaded function should return by reference ie as below: 大多数书籍都表明,对于上述运算符,重载函数应该通过引用返回,如下所示:
Integer& operator+=(const Integer&)
{
i = i + arg.i;
return *this;
}
If we return by reference then what happens to the return object reference when below statement is executed: 如果我们通过引用返回,那么当执行下面的语句时,返回对象引用会发生什么:
b += a; b + = a;
If we return by reference then what happens to the return object reference when below statement is executed:
如果我们通过引用返回,那么当执行下面的语句时,返回对象引用会发生什么:
b += a;
Nothing really. 真的没什么。 The statement gets executed, the reference is unused and
b
keep going on with its life. 该声明被执行,参考不使用,
b
跟上它的生命继续。
This interesting stuff that returning by reference allows is chaining call: you cannot do (b += b) += a
if you don't return by reference. 通过引用返回的这个有趣的东西允许链接调用:如果不通过引用返回,则不能执行
(b += b) += a
。 This would looks like this: (void) += const Integer &
, because b += b
is of type void
due to operator+=
returning void
. 这看起来像这样:
(void) += const Integer &
,因为b += b
的类型为void
因为operator+=
返回void
。
So that T& x = (y += z);
所以
T& x = (y += z);
works consistently with fundamental types. 与基本类型一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.