简体   繁体   中英

Declare / initialize static member of private nested struct

I have this example code (in a file named A.cpp ):

class O {
private:
    struct S {
        int i;
        int j;
    };

    static struct S s;
};

O::S s { 0, 1 };

I compile with g++ -c -std=c++11 A.cpp from the command line on my Mac and I get the following error:

A.cpp:11:4: error: 'S' is a private member of 'O'
O::S s { 0, 1 };
   ^
A.cpp:3:9: note: declared private here
        struct S {
               ^
1 error generated

The problem originally arose in more complicate code on a linux machine with essentially the same error. (In the "real" code the class declaration is in a header instead of all in one file, but, again, the error is the same.)

This seems like it should work. Certainly S is declared private, as the message indicates, but it is only being used in the context of the private member variable s . What's wrong here and why?

EDIT: With regard to the claimed duplicate at How to initialize private static members in C++? , the apparent difference is the scope of the inner class rather than generically how to initialize a static member variable.

This line

O::S s { 0, 1 };

Attempts to define an object ::s of the type O::S . It's not a definition of the static member. That one will look like this:

O::S O::s { 0, 1 };

S class is declared in the private section of O so code outside the class O can't access it. Specifically, you can't instantiate class S outside class O since that would constitute accessing a private declaration.

If you want to be able to create instances if S outside class O, you should declare it public.

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