-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path27friendclass.cpp
More file actions
71 lines (59 loc) · 1.94 KB
/
Copy path27friendclass.cpp
File metadata and controls
71 lines (59 loc) · 1.94 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
#include <iostream>
using namespace std;
// forward declaration : it is necessary to garauntee that a class is going to exist
class complex;
class calculator // the class that will take the data of other class is declared earlier
{
public:
int add(int a, int b)
{
return (a + b);
}
int sumReaLcomplex(complex, complex); // here the arguments should be provided when function is defined
int sumImaGcomplex(complex, complex);
};
class complex
{
int a, b;
// Individually declaring each function of a class as friend
friend int calculator ::sumReaLcomplex(complex, complex);
friend int calculator ::sumImaGcomplex(complex, complex);
/*Here, the friend function is declared which is a part of another class
the argument variables or names aren't provided as they have no garauntee unless the function is defined*/
// declaring the entire calculator class as a friend to give all functions of it access to complex's private data
friend class calculator;
public:
void setnum(int n1, int n2)
{
a = n1;
b = n2;
}
void printnum()
{
cout << "z = " << a << " + " << b << "i" << endl;
}
};
int calculator ::sumReaLcomplex(complex o1, complex o2) // declaration of a class function
{
return (o1.a + o2.a);
}
int calculator ::sumImaGcomplex(complex o1, complex o2) // declaration of a class function
{
return (o1.b + o2.b);
}
int main()
{
complex c1, c2;
c1.setnum(1, 6);
c1.printnum();
c2.setnum(7, 3);
c2.printnum();
calculator calculationR, calculationI;
int sumr = calculationR.sumReaLcomplex(c1, c2);
// here the access is done since it is function in a class scope, it only required to access data of other class
cout << "Real part of z1 + z2 is r = " << sumr << endl;
// Another friend function
int sumi = calculationI.sumImaGcomplex(c1, c2);
cout << "Imaginery part of z1 + z2 is i = " << sumi << endl;
return 0;
}