/* A class used to model Complex Numbers * Anthony Larrain * Spring 2006, csc309 */ #include #include #include using namespace std; class Complex { private: double real; double imag; public: Complex() : real(0.0), imag(0.0) {} Complex(double r) : real(r), imag(0.0) {} Complex(double r, double i) : real(r), imag(i) {} double getReal() const; double getImag() const; Complex& setReal(double r); Complex& setImag(double i); string toString() const; friend istream& operator>>(istream& is, Complex & obj); friend ostream& operator<<(ostream& os, const Complex & obj); }; Complex operator+(const Complex & operand1, const Complex & operand2); bool operator==(const Complex & operand1, const Complex & operand2); bool operator!=(const Complex & operand1, const Complex & operand2); int main(int argc, char *argv[]) { Complex c1(2.3,3.2), c2(2,1), c3; c3 = c1 + c2; cout << c3.toString() << endl; c3 = c1 + 4; cout << c3.toString() << endl; c3 = 4 + c1; cout << c3.toString() << endl; cout << (c1 == c2) << endl; cout << (c1 != c2) << endl; cout << "Enter real and imaginary parts" << endl; cin >> c3; cout << c3 << endl; system("PAUSE"); return EXIT_SUCCESS; } double Complex::getReal() const { return real; } double Complex::getImag() const { return imag; } Complex & Complex::setReal(double r){ real = r; return *this; } Complex & Complex::setImag(double i){ imag = i; return *this; } string Complex::toString() const { ostringstream str; str << real << " + " << imag << "i"; return str.str(); } Complex operator+(const Complex & operand1, const Complex & operand2) { return Complex(operand1.getReal() + operand2.getReal(), operand1.getImag() + operand2.getImag()); } bool operator==(const Complex & operand1, const Complex & operand2){ return (operand1.getReal() == operand2.getReal()) && (operand1.getImag() == operand2.getImag()); } bool operator!=(const Complex & operand1, const Complex & operand2){ return !(operand1 == operand2); } istream& operator>>(istream& is, Complex & obj) { is >> obj.real >> obj.imag; return is; } ostream& operator<<(ostream& os, const Complex & obj) { os << obj.real << " + " << obj.imag << "i"; return os; }