简体   繁体   English

为什么在重载+ =运算符时我们必须通过引用返回

[英]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.

相关问题 为什么我们必须从一元前缀运算符重载中返回const引用 - why do we have to return const reference from unary prefix operator overloading 在重载预增量运算符时,是否必须返回对象的引用? - Do I have to return a reference to the object when overloading a pre-increment operator? 为什么在赋值运算符超载时必须清空当前向量? C ++ - Why do we have to empty the current vector when overloading the assignment operator? C++ 为什么我们在赋值运算符中返回 *this 并且通常(而不是 &this)当我们想要返回对 object 的引用时? - Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object? 为什么重载运算符<<必须通过引用返回? - why overloading of operator<< must return by reference? 为什么重载“&gt;&gt;”和“&lt;&lt;”时需要通过引用传递? - Why do we need passing by reference when overloading “>>” and “<<”? 为什么在重载 = 运算符时按引用返回? - Why return by reference while overloading = operator? 为什么我们在赋值运算符重载中使用引用返回而不是在加减运算中? - Why we use reference return in assignment operator overloading and not at plus-minus ops? 为什么我必须两次传递唯一指针作为对运算符重载的引用? - Why do I have to pass a unique pointer twice as reference to an operator overloading? 运算符使用ostream和链接进行重载。 为何选择返回? - operator overloading using ostream and chaining. Why return by reference?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM