C++ examples for Class:Operator Overload
Overload arithmetic, ==, !=, >> and << operators for Complex Class
#include <iostream> class Complex {//from w w w . j av a 2s . c om friend std::ostream& operator<<(std::ostream&, const Complex&); friend std::istream& operator>>(std::istream&, Complex&); public: explicit Complex(double = 0.0f, double = 0.0f); Complex operator+(const Complex&) const; Complex operator-(const Complex&) const; Complex operator*(const Complex&)const; bool operator==(const Complex&) const; bool operator!=(const Complex&) const; private: double real; double imaginary; }; Complex::Complex(double realPart, double imaginaryPart): real(realPart), imaginary(imaginaryPart) {} Complex Complex::operator+(const Complex& operand2) const { return Complex(real + operand2.real, imaginary + operand2.imaginary); } Complex Complex::operator-(const Complex& operand2) const { return Complex(real - operand2.real, imaginary - operand2.imaginary); } Complex Complex::operator*(const Complex& operand2) const { return Complex(real * operand2.real, imaginary * operand2.imaginary); } bool Complex::operator==(const Complex& c) const { return (real == c.real && imaginary == c.imaginary); } bool Complex::operator!=(const Complex& c) const { return !(*(this) == c); } std::ostream& operator<<(std::ostream& out, const Complex& c) { out << '(' << c.real << ", " << c.imaginary << ')'; return out; } std::istream& operator>>(std::istream& in, Complex& c) { in >> c.real >> c.imaginary; return in; } int main(int argc, const char *argv[]) { Complex x; Complex y(4.3, 8.2); Complex z(3.3, 1.1); std::cout << "x: " << x; std::cout << "\ny: " << y; std::cout << "\nz: " << z; x = y + z; std::cout << "\n\nx = y + z: " << x << " = " << y << " + " << z; x = y - z; std::cout << "\n\nx = y - z: " << x << " = " << y << " - " << z; x = y * z; std::cout << "\n\nx = y * z: " << x << " = " << y << " * " << z; std::cout << "\nEnter real and imaginary parts of new z: "; std::cin >> z; std::cout << "z = " << z << std::endl; return 0; }