Reputation: 439
I'm trying to overload the addition operator,with the following prototype:
obj operator+(obj&, obj&);
this works for a+b
but triggers an error on a+b+c
g++ spits out the following error:
test.cpp:17:6: error: no match for ‘operator+’ in ‘operator+((* & a), (* & b)) + c’
test.cpp:17:6: note: candidates are:
test.cpp:10:5: note: obj operator+(obj&, obj&)
error: no match for 'operator+' in 'operator+(obj&, obj&)
note: candidates are: obj operator+(obj&, onj&)
Upvotes: 1
Views: 118
Reputation: 251
You can assume that the left hand side of an equation is always referring to "this" object which means you can change the signature of the overloaded operator to:
obj operator+(const obj &other){
// Add value of "this" to value of other
// Return obj
}
Upvotes: 0
Reputation: 20738
The problem is that your argument is a non-const reference and the operator returns a new object.
Thus, a+b
evaluates to a temporary object, which cannot bind to a non-const
reference as per the standard. Thus it cannot be passed as an argument to your operator+
. The solution is most likely to use a const
reference as @chris suggests, because you should not be modifying the operands of operator+
.
No-one would expect that and thus I personally think it would be bad style to do so.
Upvotes: 3