重载复合赋值运算符

时间:2016-02-02 10:58:13

标签: c++ operator-overloading

即使我们已经超载了+=+运营商,是否有必要重载=运算符?

2 个答案:

答案 0 :(得分:1)

您打算使用+=运营商吗?如果是,那么是的,你应该超载它。

即使您重载了operator+和赋值运算符,编译器也不会自动创建一个。您可以相互实现它们,但它们都需要实现。通常,添加和赋值将与复合赋值相同,但情况并非总是如此。

通常,当重载算术运算符(+-等)时,您应该使用相关的复合赋值(+=-=等)。

有关规范实现,请参阅cppreference上的"Binary arithmetic operators"

class X
{
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }

  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,        // passing lhs by value helps optimize chained a+b+c
                     const X& rhs) // otherwise, both parameters may be const references
  {
    lhs += rhs; // reuse compound assignment
    return lhs; // return the result by value (uses move constructor)
  }
};

这个SO Q&A有关重载的一些基本规则。

答案 1 :(得分:0)

是的,一般来说,在实现运算符重载时提供与内置类型(例如int)相同的行为是个好主意,以避免混淆。

如果没有operator+=,您必须使用operator+operator=来执行相同的操作。即使使用RVO,也会再次使用。

如果您决定实施operator+=,最好使用它来实现operator+以保持一致性。