C++ 如何返回重载二进制运算符的值
可能重复:C++ 如何返回重载二进制运算符的值,c++,c++11,C++,C++11,可能重复: 举以下例子: <type>& operator+(const <type>& rhs) { // *this.data + rhs } 运算符+(常量和rhs){ //*this.data+rhs } 如何在类型的对象中返回总和的值 如果我输入代码: <type>& operator+(const <type>& rhs) { <type> cell; switch(r
举以下例子:
<type>& operator+(const <type>& rhs) {
// *this.data + rhs
}
运算符+(常量和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;
}
运算符+(常量和rhs){
单间牢房
开关(rhs型{
双格:
{
cell.data=(双精度)cell.data+(双精度)rhs.data;
}
返回单元;
}
我返回一个临时堆栈值,并收到一条错误消息
如果我输入代码:
<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;
}
运算符+(常量和rhs){
*this.data=*this.field+rhs.data;
归还*这个;
}
我覆盖此内容,这不是添加的目的
这只是一个例子,“真实”代码要求我能够加(减,…)任意数量的输入数据类型,这反过来要求返回值能够容纳多种类型中的任何一种,它可以而且确实如此。
运算符+
应按值返回,而不是按引用返回。由于运算符不应修改左侧或右侧,因此需要第三个对象进行修改。您必须因为你不能返回一个对局部变量的引用,最好的方法就是按值返回
<type> operator+(const <type> &rhs) {
<type> sum = *this;
sum.data = sum.data + rhs.data;
return sum;
}
然后您可以按照+=
实现+
<type> operator+(const <type> &rhs) {
<type> sum = *this;
return sum += rhs;
}
另外,通过这种方式,您可以按值选择左侧,并可能利用复制/移动省略。最简单、可能也是最好的方法是将返回类型从
&
更改为