隐式赋值运算符

implicit assignment operators

本文关键字:赋值运算符      更新时间:2023-10-16

如果我的类上有运算符重载,运算符的赋值版本是否也隐式创建?

class square{
   square operator+(const square& B);
   void operator=(const square& B);
};

如在,我可以打电话吗

square A, B;
A += B;

编译器隐式决定调用operator+然后operator=

不,+=必须显式定义。


作为旁注,operator+通常应该创建一个新对象:

square operator+(const square& B);

operator=应该返回对*this的引用:

square& operator=(const square& B);

还值得注意的是,operator+通常是根据operator+=来实现的,即 operator+调用operator+=新副本。

不,运算符不是隐式定义的。但是,boost/operators.hpp定义了有用的帮助程序模板,以避免使用样板代码。他们文档中的示例:

例如,如果您声明一个类似这样的类:

class MyInt
    : boost::operators<MyInt> {
    bool operator<(const MyInt& x) const;
    bool operator==(const MyInt& x) const;
    MyInt& operator+=(const MyInt& x);
    MyInt& operator-=(const MyInt& x);
    MyInt& operator*=(const MyInt& x);
    MyInt& operator/=(const MyInt& x);
    MyInt& operator%=(const MyInt& x);
    MyInt& operator|=(const MyInt& x);
    MyInt& operator&=(const MyInt& x);
    MyInt& operator^=(const MyInt& x);
    MyInt& operator++();
    MyInt& operator--(); };

然后operators<>模板添加了十几个额外的运算符,例如 operator><=>= 和 (二进制) + .模板的双参数形式也提供给 允许与其他类型交互。

此外,还支持使用算术运算符模板隐式"推断"一组特定的运算符。

No operator+= 是它自己的运算符,必须显式定义。

请注意,operator+应返回一个新对象,而不是对原始对象的引用。原始对象应保持不变。

operator+=应返回添加所需值的原始对象。 operator+=通常更可取,因为它消除了临时对象。