// This program implements complex numbers as an abstract data type // that supports the standard complex binary operations of addition, // subtraction, multiplication, and division. #include #include class Complex { double real; double imag; public: // constructors Complex(); // default Complex(double); // only real part given Complex(double, double); // both real and imaginary parts given // other methods void write() { cout << "\n\n\t"; cout << "The Complex sum is: " << real << " + " << imag << "i" << endl; } // operator methods Complex operator+(const Complex) const; Complex operator-(const Complex) const; Complex operator*(const Complex) const; Complex operator/(const Complex) const; Complex operator+=(Complex c); }; // default constructor Complex::Complex() { real = imag = 0.0; } // constructor --real given but not imag Complex::Complex(double r) { real = r; imag = 0.0; } // constructor -- real and imag given Complex::Complex(double r, double i) { real = r; imag = i; } // Complex + as a binary operator, returns a Complex value Complex Complex::operator+(const Complex c) const { return Complex(real + c.real, imag + c.imag); } // Complex - as a binary operator Complex Complex::operator-(const Complex c) const { return Complex(real - c.real, imag - c.imag); } // Complex * as a binary operator Complex Complex::operator*(const Complex c) const { return Complex(real * c.real - imag * c.imag, imag * c.real + real * c.imag); } Complex Complex::operator/(const Complex c) const { double abs_sq = c.real * c.real + c.imag * c.imag; return Complex((real * c.real + imag * c.imag)/abs_sq, (imag * c.real - real * c.imag)/abs_sq); } Complex Complex::operator+=(Complex c) { real = real + c.real; imag = imag + c.imag; return Complex ( real + c.real, imag + c.imag); } main() { Complex c1(7.7, 5.5); Complex c2(2.2, 3.4); Complex c4(10.2, 13.5); Complex c3; clrscr(); // c3 = c1 + c2 + c4; // + for Complex variables c3 += c4; c3.write(); // write the sum getch(); // hold the output screen return (0); }