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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4605058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:54:22  来源:igfitidea点击:

Static Const Initialised Structure Array in C++ Class

c++arraysclassinitialization

提问by Sam

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

我明白如果我想要 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;
}

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?

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

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?

我该如何解决这个问题?

回答by TonyK

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

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

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

回答by CashCow

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.

一个例外是结构或私有静态成员函数需要访问类的私有成员。如果是这种情况,您至少需要在类标题中将其声明为朋友,这样一旦您必须证明它在那里,就可以通过将其声明为静态来真正失去任何东西。

回答by kbjorklu

You need to qualify ppwith c::as in

你需要有资格ppc::作为

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

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.

否则,您将尝试为全局范围定义一个新数组,而不是初始化该成员。