问题描述
我正在使用多个参数进行operator +重载.
I am doing operator+ overloading with multiple parameters as below.
#include <iostream>
using namespace std;
class Integer{
int value;
public:
Integer(int i) {value=i;};
int getValue() { return value;};
friend Integer operator+ (Integer & a, Integer & b){
Integer I (a.value+b.value);
return I;
};
};
int main() {
Integer a(1), b(2), c(3);
Integer d = a+b+c;
cout<<d.getValue()<<endl;
return 0;
}
不能编译并返回运算符+不匹配".我阅读并理解了((a + b)+ c)多参数的算法.为什么不起作用?但是,我发现了两种使它起作用的方法:
It can't be compile and return" no match for operator+". I read and understand the algorithm of multiple parameter that ((a+b)+c). Why it does not work?However, I found two ways to make it work:
friend Integer operator+ (const Integer & a,const Integer & b){
Integer I (a.value+b.value);
return I;
};
还有
friend Integer & operator+ (Integer & a,Integer & b){
Integer I (a.value+b.value);
return I;
};
但是我不知道为什么.谢谢
But I dont know why. Thank you
推荐答案
查看您的operator+
签名:
friend Integer operator+ (Integer & a, Integer & b)
// ^^^^^^^^^ ^^^^^^^^^
a
和b
是左值引用.
写作时
Integer d = a+b+c;
a+b
产生类型为Integer
的 rvalue ,该值不绑定到Integer&
.
a+b
produces an rvalue of type Integer
, which does not bind to Integer&
.
带有const Integer &
的版本可用作const
左值引用,可以绑定到左值和右值.
The version with const Integer &
works as const
lvalue references can be bound to both lvalues and rvalues.
这篇关于为什么在带有多个参数的重载运算符+中传递const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!