-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21-operator_overloading.cpp
More file actions
116 lines (104 loc) · 1.9 KB
/
Copy path21-operator_overloading.cpp
File metadata and controls
116 lines (104 loc) · 1.9 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include<iostream>
using namespace std;
class complex {
private:
int real;
int img;
public:
complex() {
real = 0;
img = 0;
}
complex(const int r, const int i)
{
real = r;
img = i;
}
void setreal(const int r)
{
real = r;
}
void setimg(const int i)
{
img = i;
}
int getreal()const
{
return real;
}
int getimg()const
{
return img;
}
void add(complex& x)
{
real += x.real;
img += x.img;
}
void operator+(complex& x) {
real += x.real;
img += x.img;
}
void operator=(complex& x)
{
real = x.real;
img = x.img;
}
void operator!() {
img = img*-1;
}
int operator[](string s) {
if (s == "real")
{
return real;
}
else
{
return img;
}
}
void print()const
{
if (img > 0)
{
cout << real << "+" << img << "i"<<endl;
}
else
cout << real << "+" <<"(" <<img<<")" << "i"<<endl;
}
};
ostream operator<<(ostream& os, complex& n)
{
n.print();
}
istream operator>>(istream& is, complex& n)
{
int r1, i1;
cin >> r1 >> i1;
n.setreal(r1);
n.setimg(i1);
}
int main()
{
complex c;
c.setimg(2);
complex d(2, 3);
c.print();
d.print();
c.add(d);//add the real and imaginary numbers in the objects a and d
c.print();
c + d;//operator overloading
//now i want to overload an operator '=' and assign the value to the
complex e;
e = c;
e.print();
!e;//operator for not e
e.print();
//overloading of '[]' operator
cout<<c["real"]<<endl;
cout << c["img"] << endl;
//overloading of '<<' '>>' ostream and istream classes respectively
complex f;
cin >> f;
cout << f;
}