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

时间:2015-04-17 22:46:20

标签: c++

虽然重载+ =运算符,为什么我们必须通过引用返回。 例如以下代码也做同样的事情

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;
}

大多数书籍都表明,对于上述操作符,重载函数应该通过引用返回,如下所示:

Integer& operator+=(const Integer&)
{
    i = i + arg.i;
    return *this;
}

如果我们通过引用返回,则执行以下语句时返回对象引用会发生什么:

b + = a;

2 个答案:

答案 0 :(得分:2)

  

如果我们通过引用返回,那么返回对象会发生什么   执行以下语句时的引用:

b += a;

没什么。语句被执行,引用未使用,b继续使用它。

这个通过引用返回的有趣内容允许链接调用:如果您不通过引用返回,则无法执行(b += b) += a。 这看起来像这样:(void) += const Integer &,因为b += b属于void,因为operator+=返回void

答案 1 :(得分:1)

因此T& x = (y += z);与基本类型一致。

相关问题