Friend functions in C can restrict access rights through access specifiers or namespaces to allow only specific functions or functions within a specific namespace to access private members of a class.
C Detailed explanation of friend functions: How to restrict the access rights of friend functions?
In C, a friend function is a special function that allows external functions to access private members of a class. It enables us to access private data or functions of one class outside another class, thus providing greater flexibility in certain situations.
Restrict the access rights of friend functions
We can limit the access rights of friend functions to private members by restricting friend declarations. There are two ways to do this:
Method 1: Using access specifiers
We can restrict using access specifiers (public, protected or private) Access permissions for friend functions. The syntax is as follows:
class MyClass { private: // 私有成员只能被友元函数访问 friend void friendFunction(); };
Method 2: Use namespace
You can also use namespaces to limit the visibility of friend functions. The syntax is as follows:
namespace MyNamespace { class MyClass { private: // 私有成员由 MyNameSpace 命名空间内部所有友元函数访问 friend class MyFriendClass; }; }
Practical case
Suppose we have the following two classes:
class Person { private: string name; int age; }; class FriendClass { public: // 可以访问私有成员,因为它是一个友元类 void printPersonDetails(Person person) { cout << person.name << ", " << person.age << endl; } };
Here, FriendClass
is A friend class of the Person
class, so it can access private members such as name
and age
.
Run the example
int main() { Person person{"John Doe", 30}; FriendClass friendObj; friendObj.printPersonDetails(person); return 0; }
Output:
John Doe, 30
The above is the detailed content of Detailed explanation of C++ friend functions: How to restrict the access rights of friend functions?. For more information, please follow other related articles on the PHP Chinese website!