C++ Friends
A friend in C++ is a special relationship that allows a non-member function or a member function of a non-current class to access a private member of a class.
Specifically, a friend can be a function, a class, or an entire namespace.
Friend declarations are usually in class definitions, and they can be used to access private or protected members outside the class.
The friendship relationship is one-way, that is, the friend function can access the private members of the class, but the class cannot access the private members of the friend function.
C++ friend function
If a function is defined somewhere other than this class, and it is declared with friend in the class body, this function is called a friend function of this class.
Friend functions can access private and protected members of a class just like member functions of a class.
A friend function can be a global function, a static member function of a class, or a member function of another class.
The declaration of a friend function is usually placed in the class definition, and the keyword friend needs to be used in the function definition to identify it as a friend function.
The role of friend functions is that when you need to access private or protected members of a class, you can do so through friend functions without having to expose these members to other functions or classes.
A friend function can be not only a general function, but also a member function in another class.
Here is a specific case of friend function:
Compilation and running results:
In the above code, a MyFriend class is defined, which has a private member variable myPrivateVar.
Then declare a friend function printPrivateVar
It can access private member variables of the class.
In the main function, a MyClass object obj is created, and the friend function printPrivateVar is called, which outputs the value of the private member variable myPrivateVar of the class.
C++ friend class
A friend class in C++ is another class declared as a friend in the class definition.
Friend classes can access private and protected members of the class, just like member functions of the class.
The declaration of a friend class is usually placed in the class definition, and the keyword friend needs to be used in the class definition to identify it as a friend class.
The role of friend classes is that when you need to access private or protected members of a class, you can do so through friend classes without exposing these members to other classes.
Unlike friend functions, friend classes can access each other's private and protected members.
Let's take a specific case of friend class:
compile and run results: