可能重复:
如何推导出仿函数的返回值类型?
给出以下示例:
<type>& operator+(const <type>& rhs) {
// *this.data + rhs
}
Run Code Online (Sandbox Code Playgroud)
如何在<type>类型的对象中返回求和的值?
如果我编码:
<type>& operator+(const <type>& rhs) {
<type> cell;
switch(rhs.type {
case DOUBLE:
{
cell.data = (double)cell.data + (double)rhs.data;
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
我返回一个临时堆栈值,并收到一条错误消息.
如果我编码:
<type>& operator+(const <type>& rhs) {
*this.data = *this.field + rhs.data;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我覆盖了这不是添加的意图.
这只是一个例子.'真正的'代码要求我能够添加(减去,...)任意数量的输入数据类型,这反过来要求返回值能够容纳几种类型的任何数据,它可以做和做.
bam*_*s53 11
operator+应按价值返回,而不是通过参考.由于操作员不应修改左侧或右侧,因此需要修改第三个对象.你必须在函数内创建一个.由于您无法返回对局部变量的引用,因此最好的方法是按值返回.
<type> operator+(const <type> &rhs) {
<type> sum = *this;
sum.data = sum.data + rhs.data;
return sum;
}
Run Code Online (Sandbox Code Playgroud)
相反,operator+=它应该通过引用返回,因为+=无论如何都应该修改左侧.
<type> &operator+= (const <type> &rhs) {
this->data += rhs.data;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以实现+在以下方面+=.
<type> operator+(const <type> &rhs) {
<type> sum = *this;
return sum += rhs;
}
Run Code Online (Sandbox Code Playgroud)
此外,通常operator+将实现为非成员函数,以便左右两侧的转换将正常工作.左侧的成员函数转换不被认为是相同的.
<type> operator+(<type> lhs, const <type> &rhs) {
return lhs += rhs;
}
Run Code Online (Sandbox Code Playgroud)
另外,通过这种方式,您可以按左侧取值,也可以利用复制/移动省略.