In C, a friend class allows all member functions of one class to access private members of another class. When declaring a friend class, use the friend class keyword, for example: OuterClass declares the inner class as a friend class: friend class inner class; only the member functions in the inner class can access the private members of OuterClass.
C Detailed explanation of friend function: How to declare a friend class
Preface
In C, friend relationships are a powerful mechanism that allows non-member functions to access private members of a class. A friend class is a special form of friend relationship that allows all member functions of one class to access the private members of another class.
Declaration of Friend Class
To declare a friend class, you need to use the friend
keyword in the definition of the class. The syntax is as follows:
class OuterClass { // 成员变量和函数 friend class InnerClass; };
This will allow all member functions in InnerClass
to access the private members of OuterClass
, but not other classes.
Practical Case
Let us consider a practical example, where OuterClass
represents a class containing sensitive data, and inner class
Represents a utility class that needs to access this data.
OuterClass:
class OuterClass { private: int secretData; // 敏感数据 public: // 可以公开访问的数据和方法 };
Inner Class:
class InnerClass { friend class OuterClass; // 声明友元类 public: void printData(OuterClass& outerObj) { // 访问OuterClass的私有成员 secretData cout << "敏感数据:" << outerObj.secretData << endl; } };
In this case, only InnerClass# Member functions in ## can access the
secretData member of
OuterClass. Other classes cannot access this private member.
Note:
can only access the public members of
inner class, while
inner class can access all members of
OuterClass.
syntax in the class definition.
The above is the detailed content of Detailed explanation of C++ friend functions: How to declare a friend class?. For more information, please follow other related articles on the PHP Chinese website!