简体   繁体   English

是在C ++中独立定义的算术/赋值运算符和复合赋值运算符

[英]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+= ? 即如果在类定义中我重载了operator+operator= ,这对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;
} 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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