// Chapter 8 of C++ How to Program // Programming Challenge 10 #include "complex.h" #include using std::ostream; using std::istream; // Constructor Complex::Complex( double r, double i ) { real = r; imaginary = i; } // end class Complex constructor // Overloaded addition operator Complex Complex::operator+( const Complex &operand2 ) const { Complex sum; sum.real = real + operand2.real; sum.imaginary = imaginary + operand2.imaginary; return sum; } // end function operator+ // Overloaded subtraction operator Complex Complex::operator-( const Complex &operand2 ) const { Complex diff; diff.real = real - operand2.real; diff.imaginary = imaginary - operand2.imaginary; return diff; } // end function operator- // Overloaded multiplication operator Complex Complex::operator*( const Complex &operand2 ) const { Complex times; times.real = real * operand2.real + imaginary * operand2.imaginary; times.imaginary = real * operand2.imaginary + imaginary * operand2.real; return times; } // end function operator* // Overloaded = operator Complex& Complex::operator=( const Complex &right ) { real = right.real; imaginary = right.imaginary; return *this; // enables concatenation } // end function operator= // Overloaded == operator bool Complex::operator==( const Complex &right ) const { return right.real == real && right.imaginary == imaginary ? true : false; } // end function operator== // Overloaded != operator bool Complex::operator!=( const Complex &right ) const { return !( *this == right ); } // end function operator!= // Overloaded << operator ostream& operator<<( ostream &output, const Complex &complex ) { output << complex.real << " + " << complex.imaginary << 'i'; return output; } // end function operator<< // Overloaded >> operator istream& operator>>( istream &input, Complex &complex ) { input >> complex.real; input.ignore( 3 ); // skip spaces and + input >> complex.imaginary; input.ignore( 2 ); return input; } // end function operator>> /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice * * Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/