Friend functions can access private members, but are restricted: they can only access private members of the current class (cannot access inherited classes), and cannot modify them directly. In actual combat, friend functions can access private members through references or pointers, such as accessing the private member name of the Student class and printing student information.
C Detailed explanation of friend functions: restrictions on access to private members
What is a friend function?
A friend function is a function that does not belong to any class, but can access all members declared in the class (including private members). Friend functions allow close interaction between different classes and enable flexible use of encapsulated classes.
Restrictions on friend functions accessing private members
There are some restrictions when friend functions access private members:
Practical case
Suppose we have a Student
class, which has a private member name
and a Public membersgetAge()
. We create a friend function printStudentInfo()
to access the private member name
and print student information.
class Student { private: string name; public: int getAge(); // 声明友元函数 friend void printStudentInfo(const Student& student); }; void printStudentInfo(const Student& student) { // 可以访问私有成员 cout << "Name: " << student.name << endl; // 不能修改私有成员 // student.name = "John Doe"; // 错误 } int main() { Student student1; student1.setName("Jane Doe"); printStudentInfo(student1); return 0; }
Output:
Name: Jane Doe
In this example, the friend function printStudentInfo()
has access to the private member name
, but it cannot be modified. In addition, it should be noted that friend functions can only access class members through references or pointers, and cannot directly use object members.
The above is the detailed content of Detailed explanation of C++ friend functions: What are the limitations of friend functions when accessing private members?. For more information, please follow other related articles on the PHP Chinese website!