We all know that private members in a class can only be accessed by member functions in the class and cannot be accessed outside the class. This reflects the encapsulation and concealment ideas of class design in C++, which is the most basic advantage of C++.
But if occasionally we really want to access these private members outside the class, it will become a lot more troublesome, and we will be in the dilemma of neither being able to access them nor being able to declare them as public types.
The emergence of friends can solve this problem very well, that is, by declaring the external function as a friend type and giving it the right to access private members within the class, it can achieve the best of both worlds. This is the meaning of friendship. It can also be seen from the literal meaning. Like "friends", it opens a green channel.
A friend object can be a global general function or a member function in another class. This is called a friend function . Not only that, a friend can also be a class, which is called a friend class .
After understanding the meaning and function of friends, let's look at how to use them in C++. For friend functions, you only need to declare the function within the class and add the friend keyword before it. This function has unique permissions and becomes a friend function.
The last thing to note is that friends do not belong to the class itself, whether they are friend functions or friend classes. Neither can use the this pointer within the class, nor can it be inherited, just like the father's friends are not necessarily the son's friends.
Next, we write a program to find the distance between two points:
#include<iostream>#include<math.h>usingnamespacestd;classPoint{private:doublex;doubley;public:Point(doublea,doubleb){x=a;y=b;}intGetPoint(){cout<<(<< x<<,<<y<<);return0;}frienddoubleDistance(Point&a,Point &b);};//Find the distance between two points doubleDistance(Point&a,Point&b){doublexx;doubleyy;xx=ax-bx;yy=ay-by;returnsqrt(xx*xx+y y*yy);}intmain(){PointA(2.0,3.0);PointB(1.0,2.0);doubledis;dis=Distance(A,B);cout<<dis<<endl;return0;}
You can observe that the function that implements the distance between two points is an external general function. Since we need to access private members in the class, we declare it as a fried friend type in the class, see the last line in the Point class. At this time, the code compiles without problems and the normal output is:
You can see the test results. You can experiment by yourself on the computer. Try not to declare it as a friend type and observe the error results.