|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | +class Complex |
| 4 | +{ |
| 5 | +private: |
| 6 | + float real; |
| 7 | + float imag; |
| 8 | +public: |
| 9 | + // Constructor |
| 10 | + Complex(float r = 0, float i = 0) |
| 11 | + { |
| 12 | + real = r; |
| 13 | + imag = i; |
| 14 | + } |
| 15 | + |
| 16 | + // Overload + operator (member function) |
| 17 | + Complex operator+(const Complex &other) const |
| 18 | + { |
| 19 | + return Complex(real + other.real, imag + other.imag); |
| 20 | + } |
| 21 | + |
| 22 | + // Overload == operator (member function) |
| 23 | + bool operator==(const Complex &other) const |
| 24 | + { |
| 25 | + return (real == other.real && imag == other.imag); |
| 26 | + } |
| 27 | + |
| 28 | + // Overload << operator (friend function) |
| 29 | + friend ostream &operator<<(ostream &out, const Complex &c); |
| 30 | + |
| 31 | + // Overload >> operator (friend function) |
| 32 | + friend istream &operator>>(istream &in, Complex &c); |
| 33 | +}; |
| 34 | + |
| 35 | +// Definition of << operator |
| 36 | +ostream &operator<<(ostream &out, const Complex &c) |
| 37 | +{ |
| 38 | + out << c.real << " + " << c.imag << "i"; |
| 39 | + return out; |
| 40 | +} |
| 41 | + |
| 42 | +// Definition of >> operator |
| 43 | +istream &operator>>(istream &in, Complex &c) |
| 44 | +{ |
| 45 | + cout << "Enter real part: "; |
| 46 | + in >> c.real; |
| 47 | + cout << "Enter imaginary part: "; |
| 48 | + in >> c.imag; |
| 49 | + return in; |
| 50 | +} |
| 51 | + |
| 52 | +// Main function |
| 53 | +int main() |
| 54 | +{ |
| 55 | + Complex c1, c2; |
| 56 | + |
| 57 | + cout << "Enter first complex number:\n"; |
| 58 | + cin >> c1; |
| 59 | + |
| 60 | + cout << "\nEnter second complex number:\n"; |
| 61 | + cin >> c2; |
| 62 | + |
| 63 | + Complex sum = c1 + c2; |
| 64 | + |
| 65 | + cout << "\nFirst complex number: " << c1 << endl; |
| 66 | + cout << "Second complex number: " << c2 << endl; |
| 67 | + cout << "Sum: " << sum << endl; |
| 68 | + |
| 69 | + if (c1 == c2) |
| 70 | + { |
| 71 | + cout << "Both complex numbers are equal.\n"; |
| 72 | + } |
| 73 | + else |
| 74 | + { |
| 75 | + cout << "Complex numbers are different.\n"; |
| 76 | + } |
| 77 | + |
| 78 | + return 0; |
| 79 | +} |
0 commit comments