0

Possible Duplicate:
How to deduce the type of the functor’s return value?

Given the following examples:

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

How do I return the value of the summation in an object of type < type>?

If I code:

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

I return a temporary stack value, and receive an error message.

If I code:

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

I overwrite this which is not the intent of the addition.

This is just an example. The 'real' code requires that I be able to add (subtract, ...) any number of input data types, which in it's turn requires that the return value is able to accommodate any on of several types, which it can and does.

4

2 回答 2

11

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

加上这种方式,您可以按价值取左侧,并可能利用复制/移动省略。

于 2012-12-11T22:56:03.597 回答
0

最简单也可能是最好的方法是将返回类型从 更改<type>&<type>

于 2012-12-11T22:57:02.937 回答