Friend: Friend class of friends function.
Friend function: does not belong to any class, just declare in the class (can be placed in private or public, no difference), tell the class, this function is your friend, of course, friends are not white: This function can access your private member variables! There is no doubt that this destroys the encapsulation of the class, there may be security problems, so what-after all, friends.
Friend class: The equivalent of making all functions inside the friend class become the friend function of another class.
For example, the following statement illustrates that Class B is a friend class of Class A:
Class a{
...
Public
Friend class B;
...
};
All member functions of Class B are friend functions of Class A that can access private and protected members of Class A.
Note When using friend classes:
(1) A friend relationship cannot be inherited.
(2) Friend relationship is one-way and not commutative. If Class B is a friend of Class A, class A is not necessarily a friend of Class B, it depends on whether there is a corresponding declaration in the class.
(3) Friend relationship does not have transitive nature. If Class B is a friend of Class A, Class C is a friend of B, Class C is not necessarily a friend of Class A, but also to see if there is a corresponding declaration in the class
(4) A friend function is not a member function of a class, so class::function name cannot be added when defined outside the class
I learned this because I used it to help my brother write homework,c++ operator overloading.
C + + friend keyword