//Complex class definition (Version 3 -- production quality) // All functions are in-line. There's no separate implementation code file. // For polar constructor and accessors, this class will use the Angle class // if the user includes it prior to including this file. #ifndef COMPLEX /* Multiple definition guard */ #define COMPLEX const Complex /* Conventional notation for constants */ #include "global.hpp" #include /* For sqrt (in rho) and atan (in theta) */ class Complex { double rp, ip; // Real & imaginary parts // Constructors and destructor // --------------------------- public: Complex(DOUBLE x = 0, DOUBLE y = 0) : rp(x), ip(y) {} // Real & imaginary #ifdef ANGLE Complex(DOUBLE r, ANGLE t) : rp(r*t.cos()), // Rho & theta ip(r*t.sin()) {} #endif // The compiler will generate an appropriate destructor, copy constructor, // and assignment operator. // Accessors // --------- double realPart() const {return rp;} double imagPart() const {return ip;} double rho() const // Magnitude of vector from {return sqrt(rp * rp + ip * ip);} // origin of complex plane #ifdef ANGLE Angle #else double #endif theta() const // Angle between vector {return atan2(imagPart(),realPart());} // & real-axis // Member operators // ---------------- Complex operator-() const // Unary minus operator {return Complex(-rp, -ip);} operator double () const // Conversion to real {assert(ip == 0); return rp;} // (Provided that value is real) Complex& operator+=(COMPLEX rs) {rp += rs.rp; ip += rs.ip; return *this;} Complex& operator-=(COMPLEX rs) {rp -= rs.rp; ip -= rs.ip; return *this;} Complex& operator*=(COMPLEX rs); Complex& operator/=(COMPLEX rs); }; // ************ 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 double abs (COMPLEX x) // Magnitude or absolute value {return x.rho();} ostream& operator<< (ostream& ls, COMPLEX rs); // Arithmetic operations // --------------------- inline Complex operator+ (COMPLEX ls, COMPLEX rs) {return Complex(ls) += rs;} inline Complex operator- (COMPLEX ls, COMPLEX rs) {return Complex(ls) -= rs;} inline Complex operator* (COMPLEX ls, COMPLEX rs) {return Complex(ls) *= rs;} inline Complex operator/ (COMPLEX ls, COMPLEX rs) {return Complex(ls) /= rs;} // Relational operator // ---------- inline bool operator== (COMPLEX ls, COMPLEX rs) {return ls.realPart() == rs.realPart() && ls.imagPart() == rs.imagPart();} #endif