Home >Backend Development >C++ >How to declare and use friend functions in C++?
A friend function in C is a special function that can access private/protected members of other classes. The friend keyword needs to be used when declaring a friend function, such as: declaring a friend function: friend void printValue(const MyClass& obj); using a friend function: a friend function can be used like a normal function and can access private/protected members; Practical case: In a logging system or testing framework, friend functions can access class private data and implement specific functions; Note: Friend functions should be used with caution, complete signatures must be specified, and protected members cannot be directly accessed unless the member Also declared as friend.
Declaring and using friend functions in C
A friend function is a special global function or method that can Access private and protected members of other classes. This is useful in situations where you need to access its internal data or operations from outside the class.
Declaring Friend Functions
To declare a friend function, use the friend
keyword as follows:
class MyClass { private: int value; public: friend void printValue(const MyClass& obj); }; // 友元函数声明 void printValue(const MyClass& obj);
The above statement makes the printValue
function a friend function of MyClass
.
Using Friend Functions
Once a friend function is declared, it can be used like any other global function. Friend functions have privileged access to private and protected members of the class. For example, in the following code, the printValue
function prints the private member value
of MyClass
:
#include <iostream> using namespace std; class MyClass { private: int value; public: friend void printValue(const MyClass& obj); }; void printValue(const MyClass& obj) { cout << "Value: " << obj.value << endl; } int main() { MyClass obj; obj.value = 10; printValue(obj); return 0; }
Output:
Value: 10
Practical Case
The following is a real-life case using friend functions:
Note
friend
. The above is the detailed content of How to declare and use friend functions in C++?. For more information, please follow other related articles on the PHP Chinese website!