Write a method to implement operator for the Complex class T
Solution
//header file
#ifndef COMPLEX
#define COMPLEX
#include <iostream>
using namespace std;
class complex {
public:
complex(double real = 0.0, double imag = 0.0);
friend complex operator+ (const complex &x, const complex &y);
friend complex operator- (const complex &x, const complex &y);
friend complex operator* (const complex &x, const complex &y);
friend complex operator/ (const complex &x, const complex &y);
friend complex operator++ ();
friend ostream& operator<<(ostream &out, const complex &z);
private:
double real;
double imag;
};
#endif
---------------------------------------------------------------------------------------------------------------------------------------------------------------
#include \"complex.h\"
complex::complex(double realx, double imagx) : real(realx), imag(imagx) {
}
complex operator+ (const complex &x, const complex &y) {
complex res;
res.real = x.real + y.real;
res.imag = x.imag + y.imag;
return res;
}
complex operator- (const complex &x, const complex &y) {
complex res;
res.real = x.real - y.real;
res.imag = x.imag - y.imag;
return res;
}
complex operator* (const complex &x, const complex &y) {
complex res;
res.real = (x.real * y.real - x.imag * y.imag);
res.imag = (x.real * y.imag + x.imag * y.real);
return res;
}
complex operator/ (const complex &x, const complex &y) {
complex res;
res.real = (x.real * y.real + x.imag * y.imag) / (y.real * y.real + y.imag * y.imag);
res.imag = (x.imag * y.real - x.real * y.imag) / (y.real * y.real + y.imag * y.imag);
return res;
}
complex operator++ () {
complex res;
res.real = x.real + 1; // adding 1 to real number
res.imag = x.imag; // imag number not modifying
return res; // reurning new number
}
ostream& operator<< (ostream &out, const complex &z) {
out << z.real << \"+\" << z.imag << \"imag\";
return out;
}

