繁体   English   中英

隐式赋值运算符[C ++]

[英]implicit assignment operators [C++]

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

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><=>=和(binary) + 还提供了模板的两个参数形式,以允许与其他类型的交互。

另外,还支持使用算术运算符模板仅隐式“推导”一组特定的运算符

没有operator+=是它自己的运算符,必​​须明确定义。

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

operator+=应该返回添加了所需值的原始对象。 通常最好使用operator+=因为它消除了一个临时对象。

暂无
暂无

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

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