简体   繁体   English

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

[英]implicit assignment operators [C++]

if i have an operator overload on my class, is the assignment version of the operator implicitly created as well? 如果我在类上有运算符重载,那么是否隐式创建了运算符的赋值版本?

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

As in, can I then call 这样,我可以打电话吗

square A, B;
A += B;

with the compiler implicitly deciding to call 'operator+' then 'operator=' ? 编译器隐式决定先调用“ operator +”,再调用“ operator =”?

No, += must be defined explicitly. 不, +=必须明确定义。


As a side note, operator+ should usually create a new object : 附带说明, operator+ 通常应创建一个新对象

square operator+(const square& B);

And operator= should return a reference to *this : 并且operator= 应该返回对*this的引用

square& operator=(const square& B);

Also worth noting that operator+ is usually implemented in terms of operator+= , ie operator+ calls operator+= on the new copy. 同样值得注意的是, operator+通常是根据operator+= ,即operator+在新副本上调用operator+=

No, the operators aren't implicitly defined. 不,运算符不是隐式定义的。 However, boost/operators.hpp defines useful helper templates to avoid boiler-plate code. 但是, boost/operators.hpp定义了有用的帮助程序模板,以避免样板代码。 Example from their docs : 他们的文档中的示例:

If, for example, you declare a class like this: 例如,如果您声明这样的类:

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--(); };

then the operators<> template adds more than a dozen additional operators, such as operator> , <= , >= , and (binary) + . 然后operators<>模板添加了十几个其他运算符,例如operator><=>=和(binary) + Two-argument forms of the templates are also provided to allow interaction with other types. 还提供了模板的两个参数形式,以允许与其他类型的交互。

In addition, there is also support for implicitly "deducing" just a specific set of operators using arithmetic operator templates . 另外,还支持使用算术运算符模板仅隐式“推导”一组特定的运算符

No operator+= is its own operator and must be defined explicitly. 没有operator+=是它自己的运算符,必​​须明确定义。

Note that operator+ should return a new object rather than a reference to the original object. 请注意, operator+应该返回一个新对象,而不是对原始对象的引用。 The original object should be left unchanged. 原始对象应保持不变。

operator+= should return the original object with the required value added. operator+=应该返回添加了所需值的原始对象。 operator+= is often preferable as it eliminates a temporary object. 通常最好使用operator+=因为它消除了一个临时对象。

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

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