Home >Backend Development >C++ >How to Access Friend Functions Defined Within a Class?

How to Access Friend Functions Defined Within a Class?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 15:45:02797browse

How to Access Friend Functions Defined Within a Class?

Accessing Friend Functions Defined Within a Class

When working with friend functions, it's essential to understand how they are defined and accessed. As friend functions are not members of a class, accessing them outside the class may require special considerations.

In the provided code snippet:

<code class="cpp">class A {

public:
    friend void fun(A a){std::cout << "Im here" << std::endl;}
    friend void fun2(){ std::cout << "Im here2" << std::endl; }
    friend void fun3();
};</code>

The friend functions fun() and fun3() are defined within the class but not declared in the global scope. While fun() can be accessed directly using Argument-Dependent Lookup (ADL) due to the argument of type A, fun2() cannot be accessed without a declaration in the global scope.

To access fun2() correctly, it should be declared globally in addition to being defined as a friend function within the class:

<code class="cpp">class A {

public:
    friend void fun(A a){std::cout << "Im here" << std::endl;}
    friend void fun2();
    friend void fun3();
};

void fun2(){ std::cout << "Im here2" << std::endl; }</code>

In this modified version, fun2() can be accessed outside the class as an ordinary function.

However, it's recommended to define friend functions in the usual manner, outside the class but declared as friends:

<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();</code>

This approach ensures that all friend functions are defined and declared correctly, making them accessible and usable as intended.

The above is the detailed content of How to Access Friend Functions Defined Within a Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn