C++类中的静态Const初始化结构数组

Sam*_*Sam 0 c++ arrays initialization class

我理解如果我想在C++的类命名空间中使用const数组,我不能这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

我必须这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我希望它们是私有的时,这需要"p"和"pp"公开.在C++中没有办法初始化私有静态数组吗?

编辑:-------------------谢谢你的答案.另外我希望这个类只是一个库,只有头文件,供主项目使用.当包含多个文件时,包括以下初始化程序会导致"多个定义"错误.

const c::p c::pp[2] =  { {1,1},{2,2} };
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

Ton*_*nyK 9

您的第一个代码段工作正常.您只需将其更改为:

const c::p c::pp[2] =  { {1,1},{2,2} };
Run Code Online (Sandbox Code Playgroud)