+ 2

Question about operator overloading

Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } can anyone explain it to me step by step?

5th Jun 2018, 8:52 PM
Asif Vudi
Asif Vudi - avatar
2 Respostas
+ 12
The call is instance based where "this + obj" is turned into "this.operator+(obj)" making the call into your listed method. It allocates the resultant complex variable. Then, adding two complex numbers is done by adding the real part of both storing the sum into the real part of the result followed by doing the same with the imaginary parts ("this." is assumed before the real and imag properties without "res." or "obj.".) Finally, the result is returned.
5th Jun 2018, 10:58 PM
John Wells
John Wells - avatar
0
its the same as Complex operator+(Conplex const& obj) { return Complex(real + obj.real, imag + obj.imag); } if you create a constructor.
5th Jun 2018, 9:03 PM
Bebida Roja
Bebida Roja - avatar