Home > Article > Backend Development > How do C++ friend functions access private members?
There are two ways for friend functions in C to access private members: declare the friend function within the class. Declare a class as a friend class so that all member functions in the class can access the private members of another class.
C Friend function’s method of accessing private members
A friend function is defined outside the class but can be accessed Functions of private members of the class. There are two ways to implement friend functions' access to private members:
1. Declare a friend function
Declare a friend function within the class, the syntax is as follows:
class ClassName { public: // 类成员... // 声明友元函数 friend void friend_function(); };
In this way, the declared friend function can access the private members of the class.
2. Declare a friend class
Declare a class as a friend class, and all member functions in the class can access the private members of another class. The syntax is as follows:
class ClassName1 { public: // 类成员... // 声明友元类 friend class ClassName2; };
All member functions declared in ClassName2
can access the private members of ClassName1
.
Practical case
Consider the following C code:
class Person { private: int age; string name; public: // 友元函数 friend void print_person_info(const Person& person); // 访问私有成员的友元函数 void print_info() const { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } }; // 友元函数外部分类的定义 void print_person_info(const Person& person) { cout << "Name: " << person.name << endl; cout << "Age: " << person.age << endl; } int main() { Person person; person.name = "John"; person.age = 30; person.print_info(); print_person_info(person); return 0; }
In this example, the print_person_info
function is a friend function , which has access to private members of the Person
class. In the Person
class, the print_info
function also accesses private members, which uses a friend function declaration.
Running the above code will output:
Name: John Age: 30 Name: John Age: 30
The above is the detailed content of How do C++ friend functions access private members?. For more information, please follow other related articles on the PHP Chinese website!