A friend function is a non-member function that has access to private or protected members. Friend functions can be used to facilitate cross-class data sharing, access private members to implement specific functions, and allow external functions to access class private data, etc.
#C Detailed explanation of friend functions: When to use friend functions?
What is a friend function?
Friend functions are non-member functions that allow access to private or protected members. Friend functions are not part of the class but have access to private members of the class.
When to use friend functions?
Using friend functions is convenient in the following situations:
Syntax
The syntax for declaring a friend function is as follows:
friend 返回类型 函数名(参数列表);
friend
The keyword is used to specify the function is a friend function.
Practical Case
Consider the following code, which defines a class with a private member data
:
class MyClass { private: int data; public: // ... };
Now, We need a friend function to access the data
member in order to modify it:
friend void modifyData(MyClass& obj, int newData) { obj.data = newData; }
The modifyData
function is declared as a friend function, so it can access the class Private member data
of MyClass
.
Note
this
pointers cannot be used. The above is the detailed content of Detailed explanation of C++ friend functions: When do you need to use friend functions?. For more information, please follow other related articles on the PHP Chinese website!