简体   繁体   中英

Are arithmetic/assignment operators and compound assignment operators independently defined in C++

Ie if within a class definition I overload operator+ or operator= does this have any effect on the operator+= ? and vice versa.

Or are these operators completely independent unless otherwise defined?

No, these operators are completely independent.

You can of course implement one using the others, but by default they're independent.

struct X
{
    X& operator = (const X&);
    X operator + (const X&) const;
    //X& operator += (const X& other) 
    //        { operator=(operator+(other)); return *this; }
};

X x, y;
x += y; //doesn't compile unless you uncomment that line

The language imposes no restriction about this - you could have an operator + that sums two objects and a += that blows up the sun and it would still be legal. On the other hand, it's strongly advised not to come up with counterintuitive operator overloads, otherwise your class would result extremely awkward to use.

Incidentally, to avoid code duplication often + is implemented in terms of +=:

A operator+(const A& right) const
{
    A ret(*this);
    ret+=right;
    return ret;
} 

不,如果您的行为是这样,则还需要重写+=运算符!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM