Friend functions can access private and protected data members of the class, but global functions cannot. Friend functions are declared in the class declaration, and global functions are declared outside the class. Use the friend keyword to declare friend functions and the extern keyword. Declare global functions. Friend functions obtain permission to access class member variables through declaration. For example, by declaring a friend function getPrivateData, you can access the private variable x of the MyClass class.
C Detailed explanation of friend functions
The difference between friend functions and global functions
In C, a friend function is a special function that can access private and protected data members declared in a class member function. In contrast, global functions are declared outside the class and have no access to private and protected data members.
The syntax of friend function
The syntax of friend function is as follows:
friend 返回类型 函数名(参数列表);
For example, declare a function that can access MyClass
Friend functions of private data members:
friend int getPrivateData(MyClass& object);
The difference between friend functions and global functions
The main differences between friend functions and global functions are as follows:
friend
keyword, while global functions are declared using the extern
keyword. Practical case
Consider a MyClass
class that contains private member variables x
:
class MyClass { private: int x; public: int getX(); void setX(int value); };
To access the private data members x
of MyClass
, we can declare a friend function:
friend int getPrivateData(MyClass& object) { return object.x; }
Use friend function
We can use friend functions to access the private data members of MyClass
:
int main() { MyClass object; object.setX(10); int privateData = getPrivateData(object); cout << "Private data: " << privateData << endl; return 0; }
Running this code will output:
Private data: 10
The above is the detailed content of Detailed explanation of C++ friend functions: What is the difference between friend functions and global functions?. For more information, please follow other related articles on the PHP Chinese website!