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;
}
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;
};
And
friend Integer & operator+ (Integer & a,Integer & b){
Integer I (a.value+b.value);
return I;
};
But I dont know why. Thank you
Look at your operator+
signature:
friend Integer operator+ (Integer & a, Integer & b)
// ^^^^^^^^^ ^^^^^^^^^
a
and b
are lvalue references .
When you write
Integer d = a+b+c;
a+b
produces an rvalue of type Integer
, which does not bind to Integer&
.
The version with const Integer &
works as const
lvalue references can be bound to both lvalues and rvalues .
Executing a+b+c;
will first invoke operator +
with a
and b
which will produce a temporary Integer
object, then invoke operator +
with that temporary object and c
. Calling operator +
second time won't be possible because a temporary object can not be passed as reference to a non-const-qualified object.
Declaring operator +
to accept non-const references does not make sense anyway because objects passes are not modified.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.