-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfriend_fun.cpp
More file actions
142 lines (111 loc) · 2.39 KB
/
Copy pathfriend_fun.cpp
File metadata and controls
142 lines (111 loc) · 2.39 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
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
/*
#include<iostream>
using namespace std;
class Complex{
int a, b;
public:
void setNum(int n1, int n2){
a = n1;
b = n2;
}
friend Complex sumComplex(Complex o1, Complex o2);
void printNum(){
cout << "Your number is: " << a << " + " << b << "i" << endl;
}
};
Complex sumComplex(Complex o1, Complex o2){
Complex o3;
o3.setNum(o1.a + o2.a, o1.b + o2.b);
return o3;
}
int main(){
Complex c1, c2, sum;
c1.setNum(1, 2);
c1.printNum();
c2.setNum(3, 4);
c2.printNum();
sum = sumComplex(c1, c2);
sum.printNum();
return 0;
}
Properties of friend functions
1. Friend functions are not member functions of a class.
2. They can access private and protected members of the class.
3. They are usually used to perform operations on objects of the class.
4. They are defined outside the class but can be declared inside the class.
5. They can be called using the object of the class or directly.
// Lecture no 27
// Friend Class and Member Friend Functions in C++
#include <iostream>
using namespace std;
class Complex;
class Calculator{
public:
int add(int a, int b)
{
return a + b;
}
int sumRealComplex(Complex, Complex);
};
class Complex
{
int a, b;
friend int Calculator :: sumRealComplex(Complex, Complex );
public:
void setNum(int n1, int n2)
{
a = n1;
b = n2;
}
void printNum()
{
cout << "Your number is: " << a << " + " << b << "i" << endl;
}
};
int Calculator :: sumRealComplex(Complex o1, Complex o2)
{
return (o1.a + o2.a);
}
int main(){
Complex o1, o2;
o1.setNum(1, 2);
o2.setNum(3, 4);
Calculator calc;
int result = calc.sumRealComplex(o1, o2);
cout << "Sum of real parts: " << result << endl;
return 0;
}
// Lecture no. 28
*/
#include<iostream>
using namespace std;
class Y; // forword decleartion
class X{
int data;
public:
void setValue(int value){
data = value;
}
friend void add(X, Y);
};
class Y
{
int num;
public:
void setValue(int value)
{
num = value;
}
friend void add(X, Y);
};
void add(X o1, Y o2) {
cout << "Summing of data X and Y object gives me "<<o1.data + o2.num;
};
int main(){
X sk;
sk.setValue(8);
Y ks;
ks.setValue(6);
add(sk, ks);
return 0;
}