我正在尝试在类的头文件中初始化一个数组:
class C {
private:
static float p[26] = {
0.09, 0.02, 0.02, 0.04, 0.12, 0.02, 0.03,
0.02, 0.09, 0.01, 0.01, 0.04, 0.02, 0.06,
0.08, 0.02, 0.01, 0.06, 0.04, 0.06, 0.04,
0.02, 0.02, 0.01, 0.02, 0.01
};
...
我从 g++ 得到以下错误:
C.h:15:33: error: a brace-enclosed initializer is not allowed here before ‘{’ token
C.h:20:9: sorry, unimplemented: non-static data member initializers
C.h:20:9: error: ‘constexpr’ needed for in-class initialization of static data member ‘p’ of non-integral type
我被迫使用c++0x
;如何在不执行 p[0]
、p[1]
等操作的情况下定义此数组?
最佳答案
您可以使用以下方法在头文件中声明类
的static
成员变量:
class C {
private:
static float p[26];
};
您可以使用以下方法在 .cpp 文件中定义它:
float C::p[26] = {
0.09, 0.02, 0.02, 0.04, 0.12, 0.02, 0.03,
0.02, 0.09, 0.01, 0.01, 0.04, 0.02, 0.06,
0.08, 0.02, 0.01, 0.06, 0.04, 0.06, 0.04,
0.02, 0.02, 0.01, 0.02, 0.01
};
关于c++ - 在C++头文件中初始化一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228369/