Description of friend mechanism of C + + class


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 
 3 #include 
 5 using namespace std;
 7 class Point
 8 {// point class declaration
10 public: / external interface
12         Point(int x=0, int y=0) : x(x), y(y) { }
14         int getX() { return x; }
16         int getY() { return y; }
18         friend float dist(Point &a, Point &b);
20 private: / private data member
22         int x, y;
24 };
26 float dist( Point& a, Point& b)
27 {
28     double x = a.x - b.x;
30     double y = a.y - b.y;
32     return static_cast(sqrt(x * x + y * y));
34 }
36 int main()
37 {
39     Point p1(1, 1), p2(4, 5);
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.


Recommended Today

Android custom view (6) handwritten a fun alphabet

Look at the effect first Screenrecorder-2021-06-29-14-25-54-6992021629143911.gif Write in two steps (1) Draw 26 letters from top to bottom (2) Intercept the touch event, change the x position of several adjacent letters according to the finger contact, and redraw the letters. (1) Draw 26 letters The first step is to draw 26 letters from top to […]