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