-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryOperatorOverloading.cpp
More file actions
57 lines (42 loc) · 975 Bytes
/
BinaryOperatorOverloading.cpp
File metadata and controls
57 lines (42 loc) · 975 Bytes
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
#include<iostream>
#include<string>
using namespace std;
/* For Binary Operator
Syntax:-
<Class on which it is called> operator <parameter>
For
<parameter> operator <Class on which it is called>
Use friend
This is reverse of Unary Operator
*/
class A {
string name;
int value;
public:
A(string name, int value) {
this->value = value;
this->name = name;
}
void print() {
cout<<"Name = "<<name<<" value = "<<value<<endl;
}
A operator+(int val) {
return A("obj2", val + value);
}
// Error since this is ambiguous with A operator+(int val)
// friend A operator+(A &obj, int val);
friend A operator+(int val, A &obj);
};
A operator+(int val, A &obj) {
return A("obj3", val + obj.value);
}
int main() {
A obj("obj1", 10);
A res = obj + 100;
// Needs friend function
A res2 = 200 + obj;
obj.print();
res.print();
res2.print();
return 0;
}