Home > Article > Backend Development > How to Access Friend Functions Defined in a C Class?
Accessing Friend Functions Defined in a Class
In C , friend functions are granted access to private and protected members of a class. The provided code defines a class A with three friend functions: fun, fun2, and fun3. While fun and fun3 can be accessed without issue, there's a problem accessing fun2.
To access fun2, you have two options:
1. Global Declaration of Friend Functions:
You can declare friend functions in the global scope after the class definition. This informs the compiler that a function exists externally and is a friend of the class. For example:
<code class="cpp">#include <iostream> class A { public: friend void fun(A a); friend void fun2(); friend void fun3(); }; void fun(A a) { std::cout << "I'm here" << std::endl; } void fun2() { std::cout << "I'm here2" << std::endl; } void fun3() { std::cout << "I'm here3" << std::endl; } int main() { fun(A()); // Works fun2(); // Now works fun3(); // Works }</code>
2. Explicit Member Function Invocation:
You can explicitly invoke friend functions as member functions of the class. However, this requires the friend functions to be marked as static (if they do not have an this parameter). For instance:
<code class="cpp">#include <iostream> class A { public: friend static void fun(A a); friend static void fun2(); friend static void fun3(); }; static void fun(A a) { std::cout << "I'm here" << std::endl; } static void fun2() { std::cout << "I'm here2" << std::endl; } static void fun3() { std::cout << "I'm here3" << std::endl; } int main() { fun(A()); // Works A::fun2(); // Works fun3(); // Works }</code>
Remember, the declaration of the friend function in the global scope is necessary, regardless of whether it's accessed explicitly or as a static member function.
The above is the detailed content of How to Access Friend Functions Defined in a C Class?. For more information, please follow other related articles on the PHP Chinese website!