【问题标题】:return type of operator+= while overloading重载时 operator+= 的返回类型
【发布时间】:2016-03-26 05:58:45
【问题描述】:

我在互联网上浏览了一些关于运算符重载的示例,其中operator+= 的返回类型为T&。因为我们不能像T a = b = c; 一样链接+=,所以可以将返回类型声明为void。使用void 时,一切似乎都正常工作。有什么情况需要避免吗?

例如:

class MyInteger{
    private:
        int x;
    public:
        MyInteger(const int& a):x(a){}
        void operator+=(const MyInteger& rhs){
            x += rhs.x;
        }
};

MyInteger a(10);
a += a;  //No need to return anything because we can't chain
a = a + (a += a);

【问题讨论】:

  • “既然我们不能链接+=”?为什么不? (((a += b) += c) += d)a += (b += (c += d)))。它与以往一样可链接。
  • @AnT 是的,但是我们不需要返回任何东西,我猜。因为更改是在 LHS 中进行的,它将可用于下一次操作。所以不需要T& 作为回报。
  • 但是如果你想把它链起来,你必须返回一些东西。
  • @AnT 你是对的,如果返回无效,就会得到error: invalid operands to binary expression ('void' and 'MyInteger')
  • @jblixr -- 为什么要违背约定? operator+= 应该返回对当前对象的引用。 MyInteger& operator+=(const MyInteger&); 此外,您可以通过以+= 实现operator +

标签: c++ c++11 operator-overloading


【解决方案1】:

您希望operator += 返回对当前对象的引用的另一个原因是您想要重载operator +。由于您正在编写一个整数类,因此如果 += 可用,但 + 不可用,这将没有多大意义。

这是operator + 的样子:

MyInteger MyInteger::operator+(const MyInteger& rhs)
{
   MyInteger temp(*this);
   return temp += rhs;  // <-- Uses operator +=
}

如果operator += 没有返回引用,上述内容将无法工作(甚至无法编译)。

【讨论】:

    【解决方案2】:

    正如@Ant 已经指出的那样,它可以被链接,但这不是唯一的考虑因素。考虑

    cout << (a += b);
    

    例如 - 如果没有回报,这将不起作用。

    算术运算符本身只不过是人类的惯例。从技术上讲,您甚至可以让+= 执行-= - 它会为您构建并可能运行(只要您遵循新的私人约定)。在 C++ 中,您应该遵循该语言的约定:您的代码的客户端将期望 += 自增,并且

    cout << (a += b);
    

    将打印出结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      相关资源
      最近更新 更多