像这样在我的类中声明静态常量数组时
static const int myArray[] = {1, 2, 3, 999};
我收到类似“类型为 const int[] 的静态数据成员的类内初始化器需要 constexpr 说明符”的错误。当我这样做并将其声明为
static constexpr int myArray[] = {1, 2, 3, 999};
它有效。为什么不能声明静态常量数组?我错过了什么?
最佳答案
题目中的declaration和definition/initialization好像有点混淆
在 C++11 之前,静态成员的定义(通常包括初始化)应该在类外完成,整数或枚举类型的静态常量除外。来自 Stroustrup's C++ FAQ :
to use in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression
即使在这种情况下,如果需要定义(例如,当获取静态成员的地址时),也应该在类外定义。
C++11 引入了 constexpr
说明符来指示编译时初始化,并允许在声明 constexpr
时在类中初始化静态成员(检查 Constant static
的引用中的静态成员 部分)。它还允许 in-class非静态成员的初始化,但具有更广泛的含义。
关于c++ - 静态常数整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479003/