0

在 Visual C++ 中,如何在类中初始化常量数组?

这是如何在类之外执行此操作的示例:

const char k_colors[] = 
{ 
    'R', 
    'G', 
    'B',
};

现在我需要如何改变它?(我尝试将静态放在它前面,但没有用)

编辑:你是对的,我应该只使用单个字符。

4

4 回答 4

3

我尝试将静态放在它前面,但没有用

您不能static在类定义中初始化成员数组(或任何成员数组)。在类定义之外执行它:

class X
{
    static const char* k_colors[3];
};

const char* X::k_colors[] = { "Red", "Green", "Blue" };
于 2012-10-05T07:39:57.550 回答
3

如果您希望它是静态的,则需要在类之外对其进行初始化:

class foo
{
public:
    static const char k_colors[3];
    foo() { }

};

const char foo::k_colors[] = {'a', 'b', 'c'};

此外,您可能希望它是 a const char *[],因为看起来您正在尝试初始化字符串,所以它是:

const char *foo::k_colors[] = {"Red", "Green", "Blue"};
于 2012-10-05T07:41:47.933 回答
1

在 C++11 中,您可以使用前面提到的构造函数初始化器列表

class A {
    const int arr[2];

    // constructor
    A() 
    : arr ({1, 2}) 
    { }
};

或者你可以使用静态常量数组

在头文件中:

class A {
    static const int a[2];
    // other bits follow
};

在源文件中(或与上述声明分开的地方)

const int A::a[] = { 1, 2 }; 

当然,您也可以随时使用std::vector<int>for循环。

于 2012-10-05T07:47:28.713 回答
0

我认为您可以通过constructor initializer列表进行初始化

参考这里

char应该是char*

从上面的链接中提取:

在 C++11 之前,您需要这样做来默认初始化数组的每个元素:

: k_colors()

对于 C++11,更推荐使用统一的初始化语法:

: k_colors{ }

这样,您实际上可以将以前无法放入的东西放入数组中:

: k_colors{"red","green"}
于 2012-10-05T07:34:09.923 回答