Write c of overloading - operator in complex numbers class-00475
This subjective question is related to the book/course vu cs302 Digital Logic Design. It can also be found in vu cs302 Mid Term Solved Past Paper No. 2.
Question 1: Write c++ of overloading - operator in complex numbers class which can work in these give situation. If we have two objects of complex number class as follows,
Complex obj1;
Complex obj3 = 47.4 - obj2;
Complex obj4 = obj2 - 47.4;
private:
double real, img;
public:
friend complex operator -(double c1, complex obj);
Complex operator - (double c1) {
Complex temp;
temp.real=real-c1;
temp.img=img-c1;
return temp;
}
Handout Page No.146
Complex obj1;
Complex obj3 = 47.4 - obj2;
Complex obj4 = obj2 - 47.4;
Answer:
We have made them as friend so that we can write them as non member functions and they ar not called with respect to complex no. Class object instead we pass both arguments (complex no. object and double value) to this function compiler invoke them according to arguments passed. Their implementation is similar as give below.
Class complex {private:
double real, img;
public:
friend complex operator -(double c1, complex obj);
Complex operator - (double c1) {
Complex temp;
temp.real=real-c1;
temp.img=img-c1;
return temp;
}
Handout Page No.146