#include #include #include #include "Complex.h" using std::cout; using std::endl; using std::ios_base; using std::istream; using std::ostream; using std::string; using std::stringstream; // This sample implementation prints diagnostic messages that // would not be included in a production class, but are helpful // for observing how the class works. namespace complex { Complex::Complex(const double real, const double imag) { cout << "constructor(" << real << "," << imag << ")"; cout << ", the constructed object is at " << this << endl; this->real_ = real; this->imag_ = imag; } Complex::Complex(const double real) { cout << "constructor(" << real << ")"; cout << ", the constructed object is at " << this << endl; this->real_ = real; this->imag_ = 0.0; } Complex::Complex(const Complex ©me) { cout << "copy constructor(copy " << ©me << ")"; cout << ", the constructed object is at " << this << endl; this->real_ = copyme.real_; this->imag_ = copyme.imag_; } Complex::~Complex() { cout << "destructor of object at " << this << endl; } Complex Complex::operator-(const Complex &a) const { Complex tmp(0,0); cout << "-: subtracting " << this << " - " << &a; cout << ", tmp is at " << &tmp << endl; tmp.real_ = this->real_ - a.real_; tmp.imag_ = this->imag_ - a.imag_; return tmp; } Complex &Complex::operator=(const Complex &a) { cout << "=operator: " << this << " = " << &a << endl; if (this != &a) { this->real_ = a.real_; this->imag_ = a.imag_; } return *this; } Complex &Complex::operator+=(const Complex &a) { cout << "+=operator: " << this << " += " << &a << endl; this->real_ += a.real_; this->imag_ += a.imag_; return *this; } Complex &Complex::operator-=(const Complex &a) { cout << "-=operator: " << this << " -= " << &a << endl; this->real_ -= a.real_; this->imag_ -= a.imag_; return *this; } // additional non-member overloaded operators in complex namespace Complex operator+(const Complex &a, const Complex &b) { Complex tmp = a; cout << "+: adding " << &a << " + " << &b; cout << ", tmp is at " << &tmp << endl; tmp += b; return tmp; } ostream &operator<<(ostream &out, const Complex &a) { cout << "<>(istream &in, Complex &a) { cout << ">>operator: to " << &a << endl; double realtmp, imagtmp; 0 // Make sure the next character is '('. if (in.peek() != '(') { in.setstate(ios_base::failbit); return in; } in.get(); // Try to read the next thing as a double. if (!(in >> realtmp)) { return in; } // Read the next three chars (' + '). if (in.get() != ' ') return in; if (in.get() != '+') return in; if (in.get() != ' ') return in; // Try to read the next token as a double ending in 'i'. string x; if (!getline(in, x, 'i')) { return in; } stringstream ss(x); if (!(ss >> imagtmp)) { return in; } // Verify the next char is ')'. if (in.peek() != ')') { in.setstate(ios_base::failbit); return in; } in.get(); a.real_ = realtmp; a.imag_ = imagtmp; return in; } } // namespace complex