Home >Backend Development >C++ >What are the declaration rules for C++ friend functions?
The rules for declaration of friend functions are as follows: the declaration must be outside the class. Can be declared as a member function or global function. Objects of a class can be passed through pointers or references.
C Declaration rules for friend functions
Friend function declaration
A friend function is a special function that can access private members of a class. To declare a friend function in C, use the friend
keyword as follows:
// 声明 MyClass 类的友元函数 printInfo() friend void printInfo(const MyClass& obj);
Declaration Rules
The following are in C Rules for declaring friend functions:
Practical case
Consider the following MyClass
class, which has private member variables _data
:
class MyClass { private: int _data; public: // ... };
We can define a friend function printInfo()
to access _data
:
// 声明 printInfo() 为 MyClass 的友元函数 friend void printInfo(const MyClass& obj) { std::cout << "Data: " << obj._data << std::endl; }
In the main function, we can instantiate MyClass
Object and call friend function to print private data:
int main() { MyClass obj; obj._data = 42; // 访问私有成员(仅在友元函数中允许) printInfo(obj); // 调用友元函数 return 0; }
Output:
Data: 42
The above is the detailed content of What are the declaration rules for C++ friend functions?. For more information, please follow other related articles on the PHP Chinese website!