C + + friend class:
Under normal circumstances, a class is not accessible to private members of another class. Just like this:
#include <iostream>class a{private: int a;public: A () { a = 1; }}; Class B:public A{public: B () { std::cout << A << std::endl; }}; int main () { B p; P (); return 0;}
This is an error: main.cpp|6|error: ' int a::a ' is private| In other words, A is private and B is not accessible.
At this point, we are going to use the concept of the friend class.
<span style= "FONT-SIZE:18PX;" > #include <iostream>class a{ friend class b;//specifies a friend of B as a. Private: int a;public: A () { a = 1; }}; Class B:public A{public: B () { std::cout << A << std::endl; }}; int main () { B p; return 0;} </span>
At this point, B will be able to access the private members of a. Even if B does not inherit to a, it can be accessed. Just like this:
<span style= "FONT-SIZE:18PX;" > #include <iostream>class a{ friend class b;//specifies a friend of B as a. Private: int a;public: A () { a = 1; }}; Class B{public: B () { a A; Std::cout << a.a << std::endl; }; int main () { B p; return 0;} </span>
In fact, however, in the development process, the programmer seldom uses the friend class, because it makes the two classes directly related to too close.
PS: Beginner C + +, there is nothing wrong place, be sure to tell me _ (: З"∠) _. I am good at correcting my studies, and I will not mislead others.
C/c++:c++ Friend class