【问题标题】:implicit assignment operators隐式赋值运算符
【发布时间】:2015-03-07 21:34:38
【问题描述】:

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

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

我可以打电话吗

square A, B;
A += B;

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

【问题讨论】:

  • 运算符重载是使代码不可读的最佳方法之一。根据Google C++ Style Guide:“一般情况下,不要重载运算符。如果需要,可以定义像 Equals() 这样的普通函数。”
  • 虽然好得多,但在创建用于表示数字的类以便能够以熟悉的格式读取代码时,这是一个问题; A = A.add(B).div(C).mul(D) 与 A = (A + B) / C * D

标签: c++ operator-overloading assignment-operator


【解决方案1】:

不,+= 必须明确定义。


作为旁注,operator+should usually create a new object

square operator+(const square& B);

还有operator=should return a reference to *this

square& operator=(const square& B);

另外值得注意的是,operator+ 通常以operator+= 的形式实现,即operator+ 在新副本上调用operator+=

【讨论】:

  • 就像在我所有的实施中一样,但我通常会离开 operator= void,因为我从未使用过多重赋值
  • 另外,不应该存在这种引用
  • 即使您到目前为止还没有使用过它,但拥有它并没有什么坏处。编译器会在你不使用它的地方优化它。
  • 很高兴知道!我真正关心的是移动数据的成本,即使我永远不会使用它,谢谢!
  • @user4578093 不要在意这样的事情,记住"premature optimization is the root of all evil"
【解决方案2】:

不,运算符不是隐式定义的。但是,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&lt;&gt; 模板添加了十几个额外的运算符,例如operator&gt;&lt;=&gt;= 和 (二进制)+。模板的两个参数形式也提供给 允许与其他类型交互。

此外,还支持使用 arithmetic operator templates 隐式“推导”一组特定的运算符。

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2012-11-02
      • 2011-08-02
      • 2019-10-06
      • 2011-11-16
      • 2013-11-30
      相关资源
      最近更新 更多