在头文件中初始化常量静态数组
问题描述:
我刚刚发现以下内容无效。在头文件中初始化常量静态数组
//Header File
class test
{
const static char array[] = { '1', '2', '3' };
};
哪里是初始化这个最好的地方?
答
//Header File
class test
{
const static char array[];
};
// .cpp
const char test::array[] = { '1', '2', '3' };
答
的最佳地点将是在源文件中
// Header file
class test
{
const static char array[];
};
// Source file
const char test::array[] = {'1','2','3'};
您可以在类的声明就像你试图做初始化整数类型;所有其他类型必须在类声明之外初始化,并且只能使用一次。
+0
不应该说“......在课堂*声明* ...”吗?我认为'.h'是声明,'.c'是定义,因此为什么只引用头中声明的整数类型会导致编译器错误:'未定义的对test :: SOME_INTEGER的引用? (我意识到这听起来超级挑剔和迂腐,我不想变得困难;我只是想确保我使用正确的术语,所以如果我错了,绝对纠正我)。 – dwanderson 2016-02-15 15:55:21
答
你总是可以做到以下几点:关于这个范式
class test {
static const char array(int index) {
static const char a[] = {'1','2','3'};
return a[index];
}
};
一对夫妇的好东西:
- 无需一个CPP文件
- 你可以做,如果你想的范围检查
- 您不必担心static initialization fiasco
答
现在,在C++ 17,可以使用内变量
A simple static data member(N4424):
struct WithStaticDataMember { // This is a definition, no outofline definition is required. static inline constexpr const char *kFoo = "foo bar"; };
在您的例子:
//Header File
class test
{
inline constexpr static char array[] = { '1', '2', '3' };
};
应该只是工作
谢谢,是不知道你是否可以在成员身边这样做。 – user174084 2010-01-22 13:07:22
定义中没有静态的,请。 – 2010-01-22 13:07:45
为什么人们强调显然不能编译的代码? – 2010-01-22 13:08:50