Defining a friend inside a class

Can I put a friend function / class definition inside another class? I mean something like this:

class Foo { friend void foo() {} // 1 friend class Bar {}; // 2 }; 

gcc compiles a friend function, but cannot compile the friend class.

+2
source share
4 answers

You can define the friend function in a friend declaration, and it has interesting behavior that cannot be obtained in any other way (if the inclusion type is a template).

You cannot define a friend class in a friend declaration, and that is not necessary. If you want to create a new inline type with full access, you can simply create a nested type. As a member, he will have full access to the closing type. The only difference is that the type will not be found at the namespace level, but you can add a typedef if necessary (or, alternatively, define a class at the namespace level and just declare friendships inside the class).

 class Outer { int x; class Inner { static void f( Outer& o ) { ox = 5; } // fine }; }; 
+6
source

n3337 11.3 / 2

The class must not be in a friend declaration. [Example:

 class A { friend class B { }; // error: cannot define class in friend declaration }; 

-end example]

But you can use something like

 class Foo { friend void foo() {} // 1 class Bar { }; friend class Bar; // 2 }; 
+3
source

You can create a nested class that, according to defect report 45, has access to private members of the class. Is that what you meant?

"The nested class is a member and as such has the same access rights as any other element."

This may not work in all compilers, because prior to this report on defects in C ++ standards, nested classes did not receive any special access.

+1
source

Change the code to: -

 class Foo { friend void foo() {} // 1 friend class Bar ; // 2 }; 
0
source

Source: https://habr.com/ru/post/984408/


All Articles