Home > Article > Backend Development > How do you access a friend function without arguments defined inside a class?
Accessing Friend Functions Defined in Class
In C , it is possible to define friend functions within a class. Friend functions are external functions that have access to the private and protected members of the class. Typically, friend functions are used to enable external modules or functions to interact with class members.
Problem:
Consider the following code:
<code class="cpp">class A { public: friend void fun(A a); // Friend function that takes an argument of type A friend void fun2(); // Friend function without arguments friend void fun3(); // Friend function declaration }; void fun(A a) { std::cout << "Im here" << std::endl; } void fun3() { std::cout << "Im here3" << std::endl; } int main() { fun(A()); // Works OK // fun2(); // Error: 'fun2' was not declared in this scope // A::fun2(); // Error: 'fun2' is not a member of 'A' fun3(); // Works OK }</code>
Question:
How can you access the friend function fun2()?
Answer:
To access the friend function fun2(), you need to explicitly define it outside the class. Currently, the definition of fun2() is missing, which is why the compiler cannot find it in the global scope.
To fix the issue, define fun2() as a global function outside the class:
<code class="cpp">void fun2() { std::cout << "Im here2" << std::endl; }</code>
With this change, you should be able to access fun2() without encountering any errors:
<code class="cpp">fun2(); // Works OK</code>
Additionally, it is recommended to follow the typical pattern of defining friend functions as separate entities outside the class for clarity and maintainability:
<code class="cpp">class A { 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(); // Leave it as a declaration int main() { fun(A()); fun2(); fun3(); }</code>
The above is the detailed content of How do you access a friend function without arguments defined inside a class?. For more information, please follow other related articles on the PHP Chinese website!