问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/47773497/why-pass-by-const-reference-in-overload-operator-with-multiple-parameters