//Complex class definition (copyright 1993, Information Disciplines, Inc.) // All functions are in-line. There's no separate implementation code file. #ifndef COMPLEX /* Multiple definition guard */ #define COMPLEX const Complex /* Conventional notation for constants */ #include /* For sqrt and trig functions */ class Complex { double _rho, _theta; // Polar coordinates // Constructors and destructor // --------------------------- public: Complex(DOUBLE x, DOUBLE y = 0) : _rho(sqrt(x*x + y*y)), _theta(atan(y/x)) {} Complex() : _rho(0), _theta(0) {} // The compiler will generate by default an appropriate destructor, // copy constructor, and assignment operator. // Accessors // --------- double realPart() const {return _rho*cos(_theta);} double imagPart() const {return _rho*sin(_theta);} double rho() const {return _rho;} double theta() const {return _theta;} // Member operators // ---------------- Complex operator-() const // Unary minus operator {Complex result; result._rho = _rho; result._theta = _theta + PI / 2.0; return result;} operator double () const // Conversion to real {assert(_theta == 0); return _rho;} // (Provided that value is real) }; // ************ End of class definition // Non-member operators and functions // ---------------------------------- // These functions are neither member nor friend functions, since they // can gain access to the component data through the accessors. inline ostream& operator<< (ostream& ls, // External representation is COMPLEX rs) // ordered pair in parens. {ls << '(' << rs.realPart() << ", " << rs.imagPart() << ')'; return ls;} // Arithmetic operations // --------------------- inline Complex operator+ (COMPLEX ls, COMPLEX rs) {return Complex(ls.realPart() + rs.realPart(), ls.imagPart() + rs.imagPart());} inline Complex operator- (COMPLEX ls, COMPLEX rs) {return ls + (-rs);} inline Complex operator* (COMPLEX ls, COMPLEX rs) {return Complex (ls.realPart() * rs.realPart() - ls.imagPart() * rs.imagPart(), ls.realPart() * rs.imagPart() + ls.imagPart() * rs.realPart());} inline Complex operator/ (COMPLEX ls, COMPLEX rs) {const double denom = rs.realPart() * rs.realPart() + rs.imagPart() * rs.imagPart(); return Complex ((ls.realPart() * rs.realPart() + ls.imagPart() * rs.imagPart()) / denom, (rs.realPart() * ls.imagPart() - rs.imagPart() * ls.realPart()) / denom);} inline Complex& operator+= (Complex& ls, COMPLEX rs) {return ls = ls + rs;} inline Complex& operator-= (Complex& ls, COMPLEX rs) {return ls = ls - rs;} inline Complex& operator*= (Complex& ls, COMPLEX rs) {return ls = ls * rs;} inline Complex& operator/= (Complex& ls, COMPLEX rs) {return ls = ls / rs;} inline double abs (COMPLEX x) {return x.rho();} // Relations // --------- inline bool operator== (COMPLEX ls, COMPLEX rs) {return ls.realPart() == rs.realPart() && ls.imagPart() == rs.imagPart();} #endif