Static Const Initialised Structure Array in C++ Cl

2019-06-14 05:16发布

I understand if I want a const array in a class namespace in C++ I cannot do:

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 must 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 "p" and "pp" to be public, when I want them to be private. Is there no way in C++ to initialise private static arrays?

EDIT: ------------------- Thanks for the answers. In addition I want this class to be a library, header files only, for use by a main project. Including the following initialiser results in " multiple definition of " errors when included by multiple files.

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

How can I solve this?

3条回答
forever°为你锁心
2楼-- · 2019-06-14 05:37

You need to qualify pp with c:: as in

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

Otherwise you're trying to define a new array to the global scope instead of initializing the member.

查看更多
干净又极端
3楼-- · 2019-06-14 05:41

Most of the time you should not have private static members and from the snippet I see this one is no exception.

Instead, you remove the struct from visibility altogether, putting it and the instance into the anonymous namespace of the compilation unit where your class functions are.

Users of the class then do not need to see implementation detail.

An exception would be where the struct or a private static member function needs access to the private members of the class. If that is the case you need to at least declare its existence as a friend in the class header so you lose nothing really by declaring it static once you have to show it is there anyway.

查看更多
SAY GOODBYE
4楼-- · 2019-06-14 05:43

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

const c::p c::pp[2] =  { {1,1},{2,2} };
查看更多
登录 后发表回答