forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperatorovld.cpp
More file actions
106 lines (84 loc) · 2.57 KB
/
Copy pathoperatorovld.cpp
File metadata and controls
106 lines (84 loc) · 2.57 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
#include<iostream>
using namespace std;
// ---------------- Start of MyClass ----------------
class MyClass {
private:
int a;
public:
MyClass(int x=0) {
a = x;
}
void print() {
cout << " print : " << a << endl;
}
// For overloaded operators defined as class members, an object of the
// Class type is the first operand (the "this" pointer)
MyClass operator+(const MyClass& that);
MyClass operator+(int x);
bool operator>(const MyClass& a);
bool operator<(const MyClass& a);
// Friends can see private members
friend ostream& operator<<(ostream& strm, const MyClass&m);
friend MyClass operator+(int x, const MyClass& that);
};
MyClass MyClass::operator+(const MyClass& that) {
MyClass ret(this->a + that.a);
return ret;
}
MyClass MyClass::operator+(int x) {
MyClass ret(this->a + x);
return ret;
}
bool MyClass::operator>(const MyClass& that) {
return this->a > that.a;
}
bool MyClass::operator<(const MyClass& that) {
return this->a < that.a;
}
// ----------------- End of MyClass -----------------
// For overloaded operators defined outside the class, each operand is passed
// in as a parameter to the function
ostream& operator<<(ostream& strm, const MyClass& m) {
strm << "{" << m.a << "}";
return strm;
}
MyClass operator+(int x, const MyClass& that) {
MyClass ret(that.a + x);
return ret;
}
int main() {
MyClass c1(1);
MyClass c2(2);
MyClass result;
int num = 10;
cout << "Initial" << endl;
c1.print();
c2.print();
result.print();
cout << endl;
cout << "result = c1 + c2" << endl;
result = c1 + c2; // result = c1.operator+(c2);
result.print();
cout << endl;
cout << "c1.operator+(c2) = " << c1.operator+(c2) << endl;
cout << "c1.operator+(num) = " << c1.operator+(num) << endl;
cout << endl;
//cout << "c1 + c2 = " << c1.a << " + " << c2.a << " = " << c1.a+c2.a << endl;
cout << "c1 + c2 = " << c1 << " + " << c2 << " = " << c1+c2 << endl;
cout << "c1 + num = " << c1 << " + " << num << " = " << c1+num << endl;
cout << "num + c2 = " << num << " + " << c2 << " = " << num+c2 << endl;
cout << endl;
if (c1 > c2) {
cout << c1 << " is greater than " << c2 << endl;
}
else {
cout << c1 << " is not greater than " << c2 << endl;
}
if (c1 < c2) {
cout << c1 << " is less than " << c2 << endl;
}
else {
cout << c1 << " is less than " << c2 << endl;
}
return 0;
}