Friends functions and friends classes of C ++
When introducing classes and objects, we have already said that classes are encapsulated. Private Members in a class can be accessed only through the member functions in the class, other functions in the program cannot directly invoke private members in the class. If a private member of the callback class is required under certain conditions, the member functions of the class must be called through objects. However, frequent calls may be cumbersome and reduce the running efficiency of the program. In order to solve this problem, we have the helper of youyuan function, but the introduction of it also damages the encapsulation and hiding of classes, so that non-member functions can be used to compile private members of the class, we do not recommend that you use friend functions.
Youyuan Function
Features:
1. In the class body, add the keyword friend before the type specifier of the function.
2. When defining in vitro, the definition format is the same as that of common functions: <类型说明符> <函数名> ( <参数表> )
3. A non-member function is called in the same way as a normal function.
4. You can directly access private members in the callback class.
For example, calculate the distance between two double-type vertices:
# Include
// Header file command # include
// The Math library function contains the file class Point {public: Point (double I, double j) // defines the constructor with two parameters {x = I; y = j ;} void Getxy () // General member function {cout <"(" <
Program Analysis:
1. The class object is initialized by calling the constructor, so that the parameters of the two objects can obtain numerical values.
2. Call the member function of an object to output coordinates.
3. Call the friend function to output the distance between two points.
Youyuan class
A friend Meta class treats a class as a friend of another class. When a class acts as a friend of another class, all member functions in the friend class are friends of another class.
Friend Function Definition Format: friend class
<类名>
Examples of programming to achieve the use of the user Meta class
# Include
// The header file contains class A // defined class A {public: friend class B; // defined friend Meta class Bvoid Set (int I) {x = I ;} // The void Display () {cout <"x =" <
Vulnerability.