简体   繁体   中英

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

Outer.hpp :

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

Outer.cpp (at top-level, eg not within a 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'm not using a compiler that is fully compliant with C++11 (Visual Studio 2010), so it is not possible to define the field at declaration.

The trick is to make Outer a friend of Inner :

Outer.hpp :

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

Now, Outer can see Inner 's type as if it weren't private even in the implementation file, so the initialization in Outer.cpp succeeds.

No, you don't need to Friend it. Bad idea.

class Inner is a private member of class Outer . There's nothing wrong with that.

The problem depends on where you've placed your definition.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM