Reputation: 879
I have received the error message.
ComplexNumber.cpp: In function ‘ComplexNumber operator-(const ComplexNumber&, const ComplexNumber&)’:
ComplexNumber.cpp:79:27: error: passing ‘const ComplexNumber’ as ‘this’ argument of ‘const ComplexNumber& ComplexNumber::operator-=(const ComplexNumber&)’ discards qualifiers [-fpermissive]
return lhs.operator-=(rhs);
I have tried changing the return of the overloaded function operator- to be ComplexNumber(real, imag), but then I receive an error message of
ComplexNumber.cpp:61:33: warning: returning reference to temporary [-Wreturn-local-addr]
I'm not sure why I'm getting the first error message. I have researched a bunch and have believe that it might have to do with const. How do I get rid of this error? Why is it happening?
The code is.
//defined -= operator
const ComplexNumber& ComplexNumber::operator-=(const ComplexNumber& rhs){
real = real - rhs.real;
imag = imag - rhs.imag;
return *this;
}
ComplexNumber operator-(const ComplexNumber& lhs, const ComplexNumber& rhs){
return lhs.operator-=(rhs);
}
Upvotes: 0
Views: 169
Reputation: 258618
Your operator -
shouldn't modify lhs
, so either create a copy, modify that and return it, or pass by value:
ComplexNumber operator-(ComplexNumber lhs, const ComplexNumber& rhs){
return lhs.operator-=(rhs);
}
I'd use this one in order to allow the compiler to perform a move instead of creating your own copy inside the function (if you pass by reference).
Upvotes: 2