#include using namespace std; // beginning of complex.h // beginning of class definition with prototypes class Complex { public: // constructors Complex(); Complex(double x, double y); void print(ostream & out) const; // Accesssor methods double getX() const; double getY() const; // input method void read(istream & in); // overload addition Complex operator+(const Complex & other) const; // overload subtraction Complex operator-(const Complex & other) const; // overload test for equality bool operator==(const Complex & other) const; private: double myX, myY; // myX is the real part and myY is the imaginary part }; // end of class definition inline ostream & operator<<(ostream & out, const Complex & z) { z.print(out); return out; } //end of complex.h // beginning of complex.cpp with function definitions // Two constructors Complex::Complex() { myX=0.0; myY=0.0; } Complex::Complex(double x, double y) { myX = x; myY = y; } // Complex::print inline void Complex::print(ostream &out) const { out << myX << " + " << myY << "i"; } // Complex::getX and getY double Complex::getX() const { return myX; } double Complex::getY() const { return myY; } // Complex::read void Complex::read(istream & in) { char ch; in >> myX; // read x coordinate in >> ch; // read + in >> myY; // read y coordinate in >> ch; // read i } // overload + and - Complex Complex::operator+(const Complex & other) const { Complex result(myX + other.getX(),myY + other.getY()); return result; } Complex Complex::operator-(const Complex & other) const { Complex result(myX - other.getX(),myY - other.getY()); return result; } //overload comparison operator bool Complex::operator==(const Complex & other) const { if (myX == other.getX() && myY == other.getY()) return true; else return false; } // end of complex.cpp // beginning of driver.cpp to test all operations int main() { Complex z1(3, 5); cout << "\nz1 is "; z1.print(cout); cout << endl; double x = z1.getX(); cout << "Real part is " << x << endl; Complex z2; cout << "Enter a complex number in the form x + yi (eg 3 + -2i) "; z2.read(cin); cout << endl << "You entered "; z2.print(cout); cout << endl; Complex z3 = z1 + z2; cout << "z1 + z2 is "; z3.print(cout); cout << endl; z3 = z1 - z2; cout << "z1 - z2 is "; z3.print(cout); cout << endl; cout << "z1 - z2 is " << z1 - z2 << endl; z3 = z2; cout << "z3 is now " << z3 << endl; if (z1 == z2) cout << "z1 and z2 are equal " << endl; else cout << "z1 and z2 are not equal " << endl; if (z2 == z3) cout << "z2 and z3 are equal " << endl; else cout << "z2 and z3 are not equal " << endl; } // end of driver.cpp