0

operator overloading

I'm doing an exercise that asks to create a Complex class and to implement sum and sub operator as well as the == operator. I'm confident with the first two, but I can't say the same for the latter. Also, what would you answer to the question: does the class need an assignment operator and a deep copy operator? class Complex { public: Complex():re (0), im(0){}; Complex(double r, double i): re(r), im(i){}; bool operator==(const Complex& right) { bool result = true; if(this != &right){ result = false; } return result; } Complex operator+(const Complex& op) { return Complex(re + op.re, im + op.im); } Complex operator-(const Complex& op){ return Complex(re - op.re, im - op.im); } private: double re; double im; };

7/15/2019 8:21:53 AM

Frangiax

4 Answers

New Answer

+2

Thank you guys!

+1

the implementation of "Complex::operator==" will be something like this ( since both the real and imaginary parts need to be equal): https://code.sololearn.com/cWKod0HB0uWD/#cpp you don't need to create a copy constructor and assignment operator, C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects but you need to define your own only if the object has pointers or any runtime allocation of the resource.

+1

Frangiax bool opetator == (const Complex& right) { // avoid self comparison if (this != &rhs) { return re == right.re && im == right.im; } return true; } When you are overloading assignment operator it generally means deep copy. You should provide copy constructor and copy assignment(overloading assignment operator) if your class contains dynamic allocated data. If your class a objects of other classes then it is the responsibility of those classes to provide proper copy constructors and copy assignment. If there are no dynamic data in your classes then compiler generated copy constructors and copy assignments are enough.

0

... Anyone?