Class friends.
C ++ proposed the concept of youyuan to address the needs of efficiency.
As long as you declare an out-of-class function as a friend of the class, you can directly access any member (public, protect, private) in the category)
This is equivalent to opening a backdoor. Since it is a backdoor, it is naturally described in this class.
Therefore, all the membership statements should be in this class.
1) declare a common function as a friend of the class,
For example:
Class
{
Private:
Int id;
Friend void display (A & a); // opens A backdoor to display
};
Void display (A &)
{
Cout <
};
2) declare a class as a friend class of this class
For example:
Class
{
Private:
Int id;
Friend class B;
};
Class B
{
Public:
Static void showA (A &)
{
Cout <}
};
3) declare a member function of a class as a membership function of this class and grant permissions to a member function.
The reference code is as follows:
# Include
Using namespace std;
Class A; // before class A is defined, class B uses class A, so the reference declaration must be made here.
Class B
{
Public:
Void showA (A & );
};
Class
{
Private:
Int id;
Public:
A (int id): id (id ){};
// Note: if it is open to other classes, other classes must have been fully defined before this!
Friend void B: showA (A & a); // use the ':' operator to indicate the member functions of the class to which the permission is granted.
};
// The member function of youyuan must be defined after the class. Otherwise, the definition of A cannot be found.
Void B: showA (A &)
{
Cout <}
Int main ()
{
A a (1 );
B B;
B. showA ();
Return 0;
}
1) All the friends are declared in the class. They only indicate the Friends function. The friends class has the right to all the members of the member class, but does not indicate that the friends function and the friends class belong to the members of the class.
2) The statement is not restricted by permissions. The statement can be performed on any row.
3) use the friend modifier. Generally, the object alias is used as the parameter.