Home > Article > Backend Development > What type members can C++ friend functions access?
In C, friend functions can access all public, protected, and private members of a class, but access to private members is restricted and can only be done when a member function of the class is called.
What is a friend function?
A friend function is a special function in C that can access private and protected members of a class. Friend functions must be declared outside the class definition.
Type members that friend functions can access
Friend functions can access the following type members:
Practical case
Consider the following code:
class MyClass { private: int m_num; public: MyClass(int num) : m_num(num) {} friend void print_num(MyClass& obj) { std::cout << obj.m_num << std::endl; } }; int main() { MyClass obj(42); print_num(obj); // 友元函数访问私有成员 return 0; }
Output result:
42
In this example, print_num () is a friend function of MyClass. It can access the private member m_num even though it is not a member function of MyClass.
Restricted Access
It should be noted that the access of friend functions to private members is restricted. Friend functions can only access private members when a member function of the class is called. In other words, friend functions cannot directly access private members from the outside.
The above is the detailed content of What type members can C++ friend functions access?. For more information, please follow other related articles on the PHP Chinese website!