[英]why can't I use reference type in the operator=?
我正在尝试为我的课程重写operator+
和operator=
。 这是我的代码:
#include <iostream>
#include <vector>
using namespace std;
class Integer {
public:
int i;
Integer operator+ (Integer&);
Integer& operator= (Integer&);
};
Integer Integer::operator+(Integer& rhs) {
Integer res;
res.i = this->i + rhs.i;
return res;
}
Integer& Integer::operator=(Integer& rhs) {
this->i = rhs.i;
return *this;
}
int main()
{
Integer i1, i2, i3;
i1.i = 1, i2.i = 2;
i3 = i1 + i2;
cout << i3.i;
}
在Visual Studio 2017中,编译器抱怨:
"E0349 no operator "=" matches these operands"
似乎Integer
对象与operator=
函数中的Integer&
不匹配。 但是它适用于operator+
函数。 这很令人困惑。
非常感谢。
i3 = i1 + i2;
返回Integer
类型的临时变量。
现在,您的operator=
采用了Integer&
。 这是对Integer
的引用。 问题在于临时对象无法绑定到非常量引用。
只要确保您更改为const Integer&
。 无论如何,这是所有运算符重载的默认值。
我将在赋值语句中对此进行细分。
i3 = i1 + i2;
发生的第一件事是对加法表达式进行求值。 这是以下代码片段:
i1 + i2
您设计了运算符重载来处理此表达式。 您的自定义加法运算符重载将返回一个新的Integer
实例。 但是,当您尝试将此新实例分配给分配过载中的参数时,就会出现问题。 这是该代码的片段。
Integer& Integer::operator=(Integer& rhs);
当在函数声明中使用引用的参数时,编译器会检查以确保此值不是临时值,以便在调用函数后该值将存在。 编译器已确定(正确)传递给此赋值语句的参数是一个临时值。 这就是为什么当您尝试执行此操作时会吐出错误的原因。
我认为使您的代码有意义的最合乎逻辑的原因是实现以下内容:
Integer& Integer::operator=(const Integer& rhs) {
this->i = rhs.i;
return *this;
}
通过添加const-specifier,您可以告诉编译器在调用函数后您不依赖rhs
来持久存在。 在那种情况下,传递给参数的值可以是一个临时值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.