After learning the friend function, let's look at the friend class again. The same principle and usage are the same. If a class A is declared as a friend class of another class B, then all member functions in class A can access members of class B. The usage method is the same, just declare it in class B.
It’s still the program function from the previous section, let’s make some changes:
#include<iostream>#include<math.h>usingnamespacestd;classPoint{private:doublex;doubley;public:Point(doublea,doubleb){x=a;y=b;}intGetPoint(){cout<<(<< x<<,<<y<<);return0;}intdistancetoLine(){}friendclassTool;};classTool{public:doubleGetX(Point&A){cout<<Ax<<endl;returnA.x;}doubleGetY(Point&A){ cout<<Ay<<endl;returnA.y;}doubledis(Point&A){cout<<sqrt(Ax*A.x+Ay*Ay)<<endl;returnsqrt(Ax*A.x+Ay*Ay); }};intmain(){PointA(2.0,3.0);ToolT;T.GetX(A);T.GetY(A);T.dis(A);return0;}
It can be seen that we have defined another tool class, which can obtain the horizontal and vertical coordinates of a point class and find the distance between this point and the origin. It is implemented by three methods and encapsulated into a class Tool. And declare the friend class in the Point class, and you can see how to use it.
Please appreciate the role of friends and understand the meaning of friends.
Finally, we summarize the advantages and disadvantages of the friend mechanism as follows:
Advantages : More convenient and faster access to private members within the class.
Disadvantages : Breaks the idea of encapsulation in C++.
Please use friends wisely!