Reputation: 3636
In order to become more familiar with C++, I'm implementing a class to manipulate complex numbers.
class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
Complex operator+=(const Complex& u);
};
I already overloaded the +
operator which works as expected:
Complex Complex::operator+(const Complex& u) const {
Complex z(_real + u._real, _imag + u._imag);
return z;
}
u=1-2i
v=2-1i
u+v=3-3i
In addition, I wanted to overload +=
as well:
Complex Complex::operator+=(const Complex& u) {
Complex z(_real + u._real, _imag + u._imag);
return z;
}
This however, does not work as expected and the result of u+=v
is u=1-2i
. Why is that the case?
Upvotes: 1
Views: 573
Reputation: 311078
Your compound assignment operator creates a new object z instead of changing the original object.
Declare the operator within the class definition like
Complex & operator+=(const Complex& u);
and define it the following way
Complex & Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}
The operator can be defined as a non-class friend function. For example
class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
friend Complex & operator+=(Complex &v, const Complex& u);
};
Complex & operator+=(Complex &v, const Complex& u)
{
v._real += u._real;
v._imag += u._imag;
return v;
}
Upvotes: 2
Reputation: 38092
First of all assign like operators should return reference to assigned value.
Secondly your code should change value of current object.
There are couple solutions:
Complex& Complex::operator+=(const Complex& u) {
*this = Complex(_real + u._real, _imag + u._imag);
return *this;
}
Or
Complex& Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}
Upvotes: 1