C++ Operator Overload relational expression == to Complex class
#include <iostream> using namespace std; // declaration section class Complex//from w ww . j av a 2s. c om { private: double realPart; // declare realPart as a double variable double imaginaryPart; // declare imaginaryPart as a double variable public: Complex(double real = 0.0, double imag = 0.0) // inline constructor { realPart = real; imaginaryPart = imag; } void showComplexValues(); // accessor prototype void assignNewValues(double real, double imag) // inline mutator { realPart = real; imaginaryPart = imag; } bool operator==(const Complex&); }; //end of class declaration // implementation section void Complex::showComplexValues() // accessor { char sign = '+'; if (imaginaryPart < 0) sign = '-'; cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i'; } bool Complex::operator==(const Complex& complex2) { if (realPart == complex2.realPart && imaginaryPart == complex2.imaginaryPart) return true; else return false; } int main() { Complex a(4, 2), b(6.5, 9.2), c(4, 2); // declare three objects if (a == b) cout << "Complex number a and b are the same." << endl; else cout << "Complex numbers a and b are not the same." << endl; if (a == c) cout << "Complex numbers a and c are the same." << endl; else cout << "Complex numbers a and c are not the same." << endl; return 0; }