How to initialize a static field whose type is a private nested class?

Outer.hpp:

class Outer { class Inner { Inner() {} }; static Inner inner; } 

Outer.cpp (at the top level, for example, not inside the function body):

 Outer::Inner Outer::inner; 

I get the following error:

 error C2248: 'Outer::Inner::inner' : cannot access private member declared in class 'Outer::Inner' 

I do not use a compiler that is fully compatible with C ++ 11 (Visual Studio 2010), so it is not possible to define a field in an ad.

+4
source share
2 answers

The trick is to make Outer friend of Inner :

Outer.hpp:

 class Outer { class Inner { Inner() {} friend Outer; } static Inner inner; } 

Outer can now see the Inner type as if it were not closed even in the implementation file, so initialization in Outer.cpp succeeds.

+4
source

No, you do not need him to do this. Bad idea.

the Inner class is a private member of the Outer class. There is nothing wrong.

The problem depends on where you placed your definition.

 Outer::Inner Outer::inner; // is fine in the global space. int main() { Outer::Inner Outer::inner; // Fails because it used as a local variable to function main. } 
+1
source

All Articles