Before explaining what a friend yuan is, Let's explain the disadvantages of the need for friends yuan and friends yuan:
Generally, for common functions, it is impossible to protect members of the category class. To do so, all the members of the class must be declared as public (shared ), however, the problem with this is that any external function can access it without any constraints, and C ++ uses the friend modifier, it allows some functions you set to operate on the data protection, avoiding setting all Class Members to public to maximize the security of data members.
Youyuan can enable normal functions to directly protect data from class member functions and avoid frequent calls of class member functions, which can save processor overhead and improve program efficiency. However, the contradiction is, even the maximum protection, it also destroys the encapsulation feature of the class, which isDisadvantages of youyuanWe do not recommend it as the CPU speed is getting faster today, but as a necessary knowledge point and a complete component of C ++, we still need to discuss it.
Declare a common function in the class and add the friend modifier before it. Then, this function becomes a friend of the class and can access all the members of the class.
Next let's look at a piece of code to see how we use youyuan to access all the members of the category.
# Include <iostream>
Using namespace STD;
Class Internet
{
Public:
Internet (char * Name, char * address)
{
Strcpy (Internet: Name, name );
Strcpy (Internet: Address, address );
}
Friend void shown (Internet & OBJ); // statement of the youyuan Function
Public:
Char name [20];
Char Address [20];
};
Void shown (Internet & OBJ) // function definition, which cannot be written. Void Internet: shown (Internet & OBJ)
{
Cout <obj. Name <Endl;
}
Void main ()
{
Internet A ("China Software Development Lab", "www.cndev-lab.com ");
Shown ();
Cin. Get ();
}
The above Code defines the membership name of object A through the membership function. The membership function cannot be regarded as a member function of the class, it is only a common function declared as a class friend, so the definition of the class external function cannot be written as void Internet: shown (Internet & OBJ.