-
Notifications
You must be signed in to change notification settings - Fork 0
/
friend function examples.cpp
151 lines (134 loc) · 2.63 KB
/
friend function examples.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include<bits/stdc++.h>
using namespace std;
namespace example1 {
class rectangle
{
private:
friend rectangle duplicate(rectangle);
int width, height;
public:
void set_values(int, int);
int area()
{
return width * height;
}
}; // end of class definition.
void rectangle::set_values(int a, int b)
{
width = a;
height = b;
}
rectangle duplicate(rectangle r)
{
rectangle t;
t.width = r.width * 2;
t.height = r.height * 2;
return t;
}
void run()
{
rectangle rect, rectb;
rect.set_values(2, 3);
cout << "the area before duplication = " << rect.area() << endl; // 6
rectb = duplicate(rect);
cout << "The area after duplication = " << rectb.area() << endl; // 24
}
}
namespace example2 {
// Combining two data member of different classes using friend
class Tri;
class Rectangle
{
friend int sum(Tri, Rectangle);
int width, height;
public:
void set_values(int a, int b)
{
width = a;
height = b;
}
};
class Tri
{
friend int sum(Tri, Rectangle);
int W, H;
public:
Tri(int a, int b)
{
W = a;
H = b;
}
};
int sum(Tri t, Rectangle r)
{
return t.W + r.width;
}
void run()
{
Rectangle r;
r.set_values(2, 3);
Tri l(5, 10);
cout << sum(l, r) << endl; // 7(5+2)
}
}
namespace example3 {
class B;
class A
{
private:
friend B sum(A, B);
int k, l;
public:
A(int a, int b)
{
k = a;
l = b;
}
};
class B
{
private:
friend B sum(A, B);
int h, i;
public:
B()
{
h = 0;
i = 0;
}
B(int c, int d)
{
h = c;
i = d;
}
int getH()
{ // public member function to access h
return h;
}
int getI()
{
return i;
}
};
B sum (A a, B b)
{
B bb;
bb.h = a.k + b.h;
bb.i = a.l + b.i;
return bb;
}
void run() {
A a1(1, 2);
B b1(2, 3);
B bb;
bb = sum(a1, b1);
// bb attributes are private, so we need a method to give us the access to them...
cout << bb.getH() << endl; // 3
cout << bb.getI() << endl; // 5
}
}
int main() {
example1::run();
example2::run();
example3::run();
}