【问题标题】:How do I return a value of an overloaded binary operator [duplicate]如何返回重载二元运算符的值[重复]
【发布时间】:2012-12-12 07:21:08
【问题描述】:

可能重复:
How to deduce the type of the functor’s return value?

举个例子:

<type>& operator+(const <type>& rhs) {
   // *this.data + rhs
}

如何在 类型的对象中返回求和值?

如果我编码:

<type>& operator+(const <type>& rhs) {
   <type> cell;
   switch(rhs.type {
   case DOUBLE:
   {
     cell.data = (double)cell.data + (double)rhs.data;  
   }
   return cell;
}

我返回一个临时堆栈值,并收到一条错误消息。

如果我编码:

<type>& operator+(const <type>& rhs) {
  *this.data = *this.field + rhs.data;
  return *this;
}

我覆盖了这不是添加的意图。

这只是一个例子。 “真实”代码要求我能够添加(减去,...)任意数量的输入数据类型,这反过来又要求返回值能够适应多种类型中的任何一种,它可以并且确实如此.

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    operator+ 应该按值返回,而不是按引用返回。由于操作员不应该修改左侧或右侧,您需要第三个对象来修改。您必须在函数内部创建那个。而且由于您不能返回对局部变量的引用,因此最好的办法是按值返回。

    <type> operator+(const <type> &rhs) {
      <type> sum = *this;
      sum.data = sum.data + rhs.data;
      return sum;
    }
    

    取而代之的是operator+=,它应该通过引用返回,因为+=无论如何都应该修改左侧。

    <type> &operator+= (const <type> &rhs) {
        this->data += rhs.data;
        return *this;
    }
    

    然后你可以用+= 来实现+

    <type> operator+(const <type> &rhs) {
      <type> sum = *this;
      return sum += rhs;
    }
    

    另外,通常operator+ 会被实现为非成员函数,这样左右两边的转换都能正常工作。与左侧的成员函数转换不一样。

    <type> operator+(<type> lhs, const <type> &rhs) {
        return lhs += rhs;
    }
    

    此外,通过这种方式,您可以按值取左侧,并可能利用复制/移动省略。

    【讨论】:

      【解决方案2】:

      最简单也可能是最好的方法是将返回类型从&lt;type&gt;&amp; 更改为&lt;type&gt;

      【讨论】:

        猜你喜欢
        • 2017-07-20
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        • 2012-03-24
        • 2012-04-26
        • 2015-01-20
        • 2011-05-27
        • 2018-10-06
        相关资源
        最近更新 更多