在头文件中初始化常量静态数组

问题描述:

我刚刚发现以下内容无效。在头文件中初始化常量静态数组

//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' }; 
+0

谢谢,是不知道你是否可以在成员身边这样做。 – user174084 2010-01-22 13:07:22

+8

定义中没有静态的,请。 – 2010-01-22 13:07:45

+1

为什么人们强调显然不能编译的代码? – 2010-01-22 13:08:50

的最佳地点将是在源文件中

// 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]; 
    } 
}; 

一对夫妇的好东西:

+1

我无法让编译器有'&a [1]'在多个对象上保持一致。 – Alex 2014-04-30 13:28:36

+0

对于字符串文字,这是完美的! – sage 2015-03-23 03:30:51

+2

您的链接“静态初始化失败”已死。 – sergiol 2015-05-28 13:54:47

现在,在C++ 17,可以使用内变量

How do inline variables work?

A simple static data member(N4424):

struct WithStaticDataMember { 
    // This is a definition, no out­of­line definition is required. 
    static inline constexpr const char *kFoo = "foo bar"; 
}; 

在您的例子:

//Header File 
class test 
{ 
    inline constexpr static char array[] = { '1', '2', '3' }; 
}; 

应该只是工作