Home >Backend Development >C++ >How to determine whether a function is a friend function?
Method to determine whether a function is a friend function: Use the keyword friend in the function declaration. Class name qualifiers are not required in function declarations.
How to determine whether a function is a friend function
A friend function is not part of a class, but it can still be accessed Private member of the class. Friend functions can be determined in the following ways:
friend
class MyClass { private: int data; friend void printData(const MyClass& obj); };
in the function declaration above In the example, the printData()
function is a friend function because the keyword friend
is used in its declaration.
Friend functions can be declared outside the class without using class name qualifiers:
class MyClass { private: int data; }; void printData(const MyClass& obj); // 友元函数声明
Consider the following example showing how to use friend functions to access private members of a class:
class MyClass { private: int data = 10; friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) { os << "data: " << obj.data; return os; } }; int main() { MyClass obj; std::cout << obj << std::endl; // 输出:data: 10 return 0; }
In this example, the operator function is a friend function that is used to overload the output operator to customize the way information of the printing class is printed.
The above is the detailed content of How to determine whether a function is a friend function?. For more information, please follow other related articles on the PHP Chinese website!