开发者

Static Const Initialised Structure Array in C++ Class

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 follo开发者_如何转开发wing 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?


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

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜