For a class without defining public access permissions, it is often useful for other classes to operate on its private members. For example, if you write a binary treeCodeNode is a node class. It is convenient to allow functions connected to multiple nodes to access private members of a node without calling the public method.
Friend classes)
The friend keyword in C ++ is used to specify other classes (OR) functions in a class to directly access private and protected members in the class.
You can specify as follows:
Friend class Aclass;
Note: the Declaration of friend in the class can control the domain of public, protected, and private without affecting the effect. For example, if you have such a declaration in the protected field, the Aclass class can also access the private members of the class.
Here is an example:
Class node {PRIVATE: int data; int key; //... friend class binarytree; // class binarytree can now access data directly };
In this way, the binarytree can directly access the private member in the node, as shown below:
Class binarytree {PRIVATE: node * root; int find (INT key) ;}; int binarytree: Find (INT key) {// check root for null... if (root-> key = Key) {// No need to go through an accessor function return root-> data;} // perform rest of find}
Friend functions (youyuan function)
The functions of the friend functions and the friend functions are the same. It allows a function to access the private and protected member variables in the class without using its public interface.
You can declare:
Friend return_type class_name: function (ARGs );
Here is an example:
Class node {PRIVATE: int data; int key; //... friend int binarytree: Find (); // only binarytree's find function has access };
In this way, the find method can directly access the private member variables in the node, while other methods in the binarytree cannot directly access the member variables of the node. (This is the difference between the membership class and the membership function)