Static Const Initialized Structural Array in C ++ Class

I understand that I want the const array in the class namespace in C ++ I could not:

class c { private: struct p { int a; int b; }; static const p pp[2]; }; const c::p pp[2] = { {1,1},{2,2} }; int main(void) { class c; return 0; } 

I have to do:

 class c { public: struct p { int a; int b; }; static const p pp[2]; }; const c::p pp[2] = { {1,1},{2,2} }; int main(void) { class c; return 0; } 

But this requires that p and pp be publicly accessible when I want them to be private. Is there no way in C ++ to initialize private static arrays?

EDIT: ------------------- Thanks for the answers. In addition, I want this class to be a library, only header files, for use in the main project. Enabling the following initializer leads to a "multiple definition" of errors when including multiple files.

 const c::pc::pp[2] = { {1,1},{2,2} }; 

How can i solve this?

0
source share
3 answers

Your first piece of code works fine. You just need to change it to:

 const c::pc::pp[2] = { {1,1},{2,2} }; 
+9
source

In most cases, you should not have private static members, and from this fragment I see that this is not an exception.

Instead, you completely remove the structure from visibility by placing it and the instance in the anonymous namespace of the compilation unit where your class functions are executed.

Class users then do not need implementation details.

The exception will be that the struct or private static member function requires access to private members of the class. If so, you need to at least declare your existence as a friend in the class header, so you don’t lose anything by declaring it static as soon as you need to show that it is all the same.

+2
source

You need to qualify pp with c:: , as in

const c::pc::pp[2] = { {1,1},{2,2} };

Otherwise, you are trying to define a new array for the global scope instead of initializing the member.

0
source

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


All Articles