Code /* Complex.cpp CIS 250 David Klick 2009-02-23 Implementation of Complex number class. Please note that comparing complex numbers for ordering does not make much sense, so <, <=, >, >= are just made-up so we can demonstrate how those operators can be overloaded. */ #include "Complex.h" // constructors Complex::Complex() { init(0.0, 0.0); } Complex::Complex(const double r, const double i) { init(r, i); } // shared initialization routine called by constructors void Complex::init(const double r, const double i) { real = r; imag = i; } // accessor methods double Complex::getReal() const { return real; } double Complex::getComplex() const { return imag; } // overloaded relational operators bool Complex::operator==(const Complex& c) const { return real==c.real && imag==c.imag; } bool Complex::operator!=(const Complex& c) const { return real!=c.real || imag!=c.imag; } bool Complex::operator<(const Complex& c) const { return real(const Complex& c) const { return real>c.real || (real==c.real && imag>c.imag); } bool Complex::operator<=(const Complex& c) const { return real=(const Complex& c) const { return real>c.real || (real==c.real && imag>=c.imag); } // overloaded preincrement and predecrement operators Complex Complex::operator++() { real += 1.0; return *this; } Complex Complex::operator--() { real -= 1.0; return *this; } // overloaded postincrement and prostdecrement operators Complex Complex::operator++(int) { Complex tmp(real, imag); real += 1.0; return tmp; } Complex Complex::operator--(int) { Complex tmp(real, imag); real -= 1.0; return tmp; } // overloaded math operators Complex Complex::operator+(const Complex& c) const { Complex tmp(real+c.real, imag+c.imag); return tmp; } Complex Complex::operator-(const Complex& c) const { Complex tmp(real-c.real, imag-c.imag); return tmp; } Complex Complex::operator*(const Complex& c) const { Complex tmp; tmp.real = real*c.real - imag*c.imag; tmp.imag = real*c.imag + imag*c.real; return tmp; } Complex Complex::operator/(const Complex& c) const { Complex tmp; double y = c.real*c.real + c.imag*c.imag; tmp.real = (real*c.real + imag*c.imag) / y; tmp.imag = (real*-c.imag + c.real*imag) / y; return tmp; } ostream& operator<<(ostream& strm, const Complex& c) { strm << c.real; if (c.imag < 0.0) strm << " - " << -c.imag << 'i'; else if (c.imag == 1.0) strm << " + i"; else strm << " + " << c.imag << 'i'; return strm; } istream& operator>>(istream& strm, Complex& c) { cout << "Enter real part of number: "; strm >> c.real; cout << "Enter imaginary part of number: "; strm >> c.imag; return strm; }