/* University College London Dept of Physics Course in C++ 3C59 | all rights reserved 2000 | | Utility: Complex class: implementation | | | Author: P.Clarke */ #include #include "Complex.h" // --------------------- // Default Constructor Complex::Complex( ) { real = 0; imag = 0; } // --------------------- // Main constructor Complex::Complex( float r, float i ) { real = r ; imag = i ; } // ----------------------- // Copy constructor Complex::Complex( const Complex& src ) { real = src.real ; imag = src.imag ; } // ------------------------ // Overloaded operators that can return references //........... // operator= Complex& Complex::operator=( const Complex& rhs ) { real = rhs.real ; imag = rhs.imag ; return *this ; } // ............... // operator += Complex& Complex::operator+=( const Complex& rhs ) { real += rhs.real ; imag += rhs.imag ; return *this ; } // -------------------- // Overloaded operators which cannot return references // ................ // operator + : written in most obvious way Complex Complex::operator+( const Complex& rhs ) { Complex result ; result.real = real + rhs.real ; result.imag = imag + rhs.imag ; return result ; } // ................ // operator - : written to use this-> // but is same as operator+ really Complex Complex::operator-( const Complex& rhs ) { Complex result ; result.real = this->real - rhs.real ; result.imag = this->imag - rhs.imag ; return result ; } // ................ // operator * : Complex Complex::operator*( const Complex& rhs ) { Complex result ; result.real = (real*rhs.real) - (imag*rhs.imag) ; result.imag = (real*rhs.imag) + (imag*rhs.real) ; return result ; } // ................ // operator / Complex Complex::operator/( const Complex& rhs ) { Complex result ; float rhsSquared = rhs.real*rhs.real + rhs.imag*rhs.imag ; result.real = ( real*rhs.real + imag*rhs.imag) / rhsSquared ; result.imag = (-real*rhs.imag + imag*rhs.real) / rhsSquared ; return result ; } // ----------------------- // To print out a complex number void Complex::print() { std::cout << " complex number: " << real << " + i " << imag << std::endl ; }