Friend functions are non-member functions that have access to private members of a class. The scope of permissions is limited to the class to which they belong. They are declared using the friend keyword. As in the example, the addMoney function is declared as a friend of the BankAccount class and can access and operate on the private member balance.
C The scope of authority of friend function
What is a friend function?
A friend function is a special non-member function that can access class members (private or protected) that are normally only accessible by class members. Similar to member functions, friend functions have the ability to access the internal representation of a class.
Permission scope
The permission scope of a friend function is limited to the class in which it is declared as a friend function. Friend functions cannot access private or protected members of other classes.
Declaring friend functions
In order to declare a function as a friend function, you can use the friend
keyword, as follows:
class MyClass { private: int privateMember; public: // 声明一个友元函数 friend void myFriendFunction(MyClass& obj); };
Practical case
Consider a class that uses friend functions to change private members:
class BankAccount { private: int balance; public: // 友元函数可以访问私有成员 friend void addMoney(BankAccount& account, int amount); }; // 友元函数的定义 void addMoney(BankAccount& account, int amount) { account.balance += amount; }
In this example, addMoney
The function is declared as a friend of the BankAccount
class, so it can access the class's private member balance
and increment its value.
The above is the detailed content of What is the scope of permissions of C++ friend functions?. For more information, please follow other related articles on the PHP Chinese website!