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?
Your compound assignment operator creates a new object z instead of changing the original object.
Declare the operator within the class definition like
and define it the following way
The operator can be defined as a non-class friend function. For example