2016-02-02 72 views
1

即使我们已经超载了+=运算符,是否有必要过载运算符+=超载复合赋值运算符

+1

做加法然后赋值与'+ ='不是一回事。然后最终的结果*可能*是相同的,但不同的事情正在发生。如果任何重载操作符有副作用(有意或无意),这一点尤其重要。 –

+0

谢谢@JoachimPileborg – Walidix

回答

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了一些基本的规则超载。

+0

谢谢你的答案@Niall – Walidix

+0

@WalidSalhi。我的荣幸。 – Niall

0

是的,在总体上是一个好主意,提供内建类型(如int)时实现运算符重载,以避免混淆相同的行为。

并且没有operator+=,您必须使用operator+operator=来做同样的事情。即使使用RVO,也会再次应用副本。

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

+0

谢谢你的回答@songyuanyao – Walidix

+0

@WalidSalhi不客气。 – songyuanyao