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:
1 2 3 4 5 6 7 |
|
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:
1 2 3 4 5 6 7 |
|
All member functions declared in ClassName2
can access the private members of ClassName1
.
Practical case
Consider the following C code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
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:
1 2 3 4 |
|
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!