-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoverloading.cpp
59 lines (47 loc) · 1.33 KB
/
overloading.cpp
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
//code by vishwa
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
Complex(float r = 0.0, float i = 0.0) : real(r), imag(i) {}
// Overload + operator to add two complex numbers
Complex operator + (const Complex &obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
// Overload - operator to subtract two complex numbers
Complex operator - (const Complex &obj) {
Complex temp;
temp.real = real - obj.real;
temp.imag = imag - obj.imag;
return temp;
}
// Function to display complex number
void display() {
if (imag >= 0)
cout << real << " + " << imag << "i" << endl;
else
cout << real << " - " << -imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 2.5), c2(1.6, 4.8);
cout << "First complex number: ";
c1.display();
cout << "Second complex number: ";
c2.display();
// Using overloaded + operator
Complex c3 = c1 + c2;
cout << "\nAfter adding c1 and c2: ";
c3.display();
// Using overloaded - operator
Complex c4 = c1 - c2;
cout << "After subtracting c2 from c1: ";
c4.display();
return 0;
}