C++中单个元素的静态数组初始化

2022-01-19 00:00:00 gcc initialization static c c++

以下代码适用于 GCC 的 C 编译器,但不适用于 C++ 编译器.在 C++ 中是否有实现相同结果的捷径"?

The following code works with GCC's C compiler, but not with the C++ compiler. Is there a "shortcut" to achieve the same result in C++?

int array[10] = {
    [1] = 1,
    [2] = 2,
    [9] = 9
};

嗯,我发现了这一点,澄清了一切.http://eli.thegreenplace.net/2011/02/15/array-initialization-with-enum-indices-in-c-but-not-c/

Humm, I found this, clarifies everything. http://eli.thegreenplace.net/2011/02/15/array-initialization-with-enum-indices-in-c-but-not-c/

推荐答案

这种初始化形式只在C99标准中定义.它确实不适用于C++.所以,你必须一个一个地分配你的元素:

This form of initialization is only defined in the C99 standard. It does not apply to C++. So, you'll have to assign your elements one-by-one:

int array[10] = { 0 };
array[1] = 1;
array[2] = 2;
array[9] = 9;

相关文章