The following is a description of the friend mechanism of C + + class (access to class private and protected members). It should be noted that the friend mechanism should not be used or used as little as possible. Although it will provide a certain degree of efficiency, it will bring problems of data security.
Friends of class
Friends areC++Provides a mechanism to destroy data encapsulation and data hiding.
By declaring a module as a friend of another module, a module can reference information that is hidden in another module. You can use friend functions and friend classes.
In order to ensure the integrity of data and the principle of data encapsulation and hiding, it is recommended to avoid or use less friends as far as possible.
friend function
Friend functions are defined by keywords in class declarationsfriendA non member function that can be accessed through the object name in its function bodyprivate andprotectedmember
Function: increase flexibility, so that programmers can make reasonable choices in encapsulation and rapidity.
Members in an object must be accessed by object name.
For example: use friend function to calculate the distance between two points
1 #include
2
3 #include
4
5 using namespace std;
6
7 class Point
8 {// point class declaration
9
10 public: / external interface
11
12 Point(int x=0, int y=0) : x(x), y(y) { }
13
14 int getX() { return x; }
15
16 int getY() { return y; }
17
18 friend float dist(Point &a, Point &b);
19
20 private: / private data member
21
22 int x, y;
23
24 };
25
26 float dist( Point& a, Point& b)
27 {
28 double x = a.x - b.x;
29
30 double y = a.y - b.y;
31
32 return static_cast(sqrt(x * x + y * y));
33
34 }
35
36 int main()
37 {
38
39 Point p1(1, 1), p2(4, 5);
40
41 cout <
Friend class
If a class is a friend of another class, all members of this class can access the private members of the other class.
Declaration syntax: use the friend class name in another classfriendModification description.
The friend relationship of a class is one-way
If statementBClass isAFriends of class,BThe member functions of the class can be accessedAClass private and protected data, butAThe member function of the class cannot be accessedBPrivate and protected data of class.