#include "complex.h" // do not copy interface #include // access: sqrt using namespace std; // ok within implementation int Complex::cplxObjCnt = 0; // define and initialize static variable // interface implementations Complex::Complex( double r, double i ) { re = r; im = i; cplxObjCnt += 1; } double Complex::real() const { return re; } double Complex::imag() const { return im; } Complex Complex::conjugate() const { return Complex( re, -im ); } double Complex::abs() const { return sqrt( re * re + im * im ); } void Complex::stats() { cout << cplxObjCnt << endl; } Complex operator+( Complex a, Complex b ) { return Complex( a.re + b.re, a.im + b.im ); } Complex operator-( Complex a, Complex b ) { return Complex( a.re - b.re, a.im - b.im ); } Complex operator*( Complex a, Complex b ) { return Complex( a.re * b.re - a.im * b.im, a.im * b.re + a.re * b.im ); } Complex operator/( Complex a, Complex b ) { double dem = b.re * b.re + b.im * b.im; return Complex( (a.re * b.re + a.im * b.im) / dem, (a.im * b.re + a.re * b.im) / dem ); } bool operator==( Complex a, Complex b ) { return a.re == b.re && a.im == b.im; } bool operator!=( Complex a, Complex b ) { return ! (a == b); // reuse code in == } istream &operator>>( istream &is, Complex &c ) { return is >> c.re >> c.im; } ostream &operator<<( ostream &os, const Complex c ) { // let negative values, including negative zero, print the "-" sign for the imaginary value return os << c.re << (c.im < 0 || (c.im == 0.0 && signbit(c.im)) ? "" : "+") << c.im << "i"; }