-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54.cpp
124 lines (106 loc) · 2.65 KB
/
54.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
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
117
118
119
120
121
122
123
#include <iostream>
#include <iomanip>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
cout << "Constructor" << endl;
feet = f;
inches = i;
}
Distance operator+(int); //d2 + 5 d2.operator+(5)
Distance operator-(Distance);
Distance operator=(Distance);
bool operator==(Distance);
Distance operator()(int, int);
friend Distance operator+(Distance, Distance);
friend ostream& operator<<( ostream&, const Distance& );
friend istream& operator>>( istream&, Distance& );
};
//D1 + D2 operator+(D1,D2)
Distance operator+(Distance d1,Distance d2)
{
cout << "Calling Friend Function" << endl;
Distance d3;
d3.inches = d1.inches + d2.inches;
d3.feet = d1.feet + d2.feet;
if(d3.inches >= 12)
d3.feet++;
d3.inches = d3.inches % 12;
return d3;
}
Distance Distance :: operator+(int d) //D3 = 6 + D5
{
Distance d3;
d3.feet = feet + d;
d3.inches = inches;
return d3;
}
//D1 - D2 D1.operator-(D2) operator-(D1, D2)
Distance Distance :: operator-(Distance d2)
{
int iLen1, iLen2;
iLen1 = feet * 12 + inches;
iLen2 = d2.feet * 12 + d2.inches;
if(iLen1 < iLen2)
{
cout << "Wrong Input" << endl;
}
else
{
Distance d3;
d3.inches = (iLen1-iLen2)%12;
d3.feet = (iLen1-iLen2)/12;
return d3;
}
}
// D1 = D2 D1.operator=(D2) D1 = D2 = D3
Distance Distance :: operator=(Distance d2)
{
inches = d2.inches;
feet = d2.feet;
return *this;
}
bool Distance :: operator==(Distance d2)
{
if(inches == d2.inches && feet == d2.feet)
return true;
return false;
}
//cout << D1 operator<<(cout, D1)
//cout << D1 << D2;
//cannot use member function approach first parameter is not of Distance Type
ostream& operator<<(ostream &output, const Distance &D)
{
output << "F : " << setw(2) << D.feet << " --- " << "I : " << setw(2) << D.inches;
return output;
}
// cin >> D3; operator>>(cin, D3)
istream& operator>>(istream &input, Distance &D)
{
input >> D.feet >> D.inches;
return input;
}
int main()
{
Distance D1(11, 6), D2, D3, D4, D5;
cout << "First Distance :\t" << D1 << endl;
cout << "Enter the value of Second Distance object : " ;
cin >> D2;
D3 = D1 + D2; //D1.operator+(D2)
D4 = D1 - D2;
cout << "First Distance :\t" << D1 << endl;
cout << "Second Distance :\t" << D2 << endl;
cout << "Sum Distance :\t\t" << D3 << endl;
cout << "Diffference : \t\t" << D4 << endl;
return 0;
}