Is there a difference if we define a friend function inside or outside the class

What is the difference between a friend function definition inside a class or a declaration inside and a definition outside the class. Also, why is this possible in defining a definition within a class, since the friend function is not a member of the class.

+5
source share
6 answers

Friend functions defined within a class can only be viewed through ADL when called from outside the class. Functions defined outside the class can be found even without ADL.

+8
source

As long as a friend function is declared inside the class (it should be), it does not matter where it is defined.

, friend inline.

( ++ 11, §11.3/7):

, , () , . , ,

+5

, , , .

0

   , , , . . , , () , . .

++ 11, [class.friend], №6-7

0

.

++ 11 §11.4/5

, , () , . , (3.4.1).

++ 17 §14.3/7

(10.1.6). () . , (6.4.1).

cppreference [ -], f1 , f2 .

int i = 3;
struct X {
    friend void f1(int x) {
        i = x; // finds and modifies X::i
    }
    friend inline void f2(int);
    static const int i = 2;
};

inline void f2(int x) {
    i = x; // finds and modifies ::i
}

, . - , . , f2 f1, .

0

It is incorrect to define a friend function inside a class .

We use a friend function to provide access to private members of a function class.

If we define a friend function within a class, then in a sense it becomes a member of the class data , and we know that the data member of its own class has access to its private members.

Therefore, if you really want to use the friend concept in C ++, declare it outside the private class.

0
source

All Articles