我正在将一些C代码移植到C++,并且无法解决处理子对象初始化的特定问题。
下面的代码是我的意思的一个例子:
#include <stdio.h>
#define MY_INDEX 1
#define MY_OTHER_INDEX 3
/* Structure declaration */
struct my_struct
{
int a;
int b;
int c;
};
/* Array declaration and initialization */
struct my_struct my_array[] =
{
[0] = (struct my_struct) {0, },
[MY_INDEX] = ((struct my_struct) {
.a = 10,
.b = 20,
.c = 30
}),
[MY_OTHER_INDEX] = ((struct my_struct) {
.a = 42,
.b = 42,
.c = 42
})
};
/** Test code */
int
main(void)
{
unsigned int i;
for (i = 0; i < sizeof(my_array)/sizeof(struct my_struct); i++)
printf("Index %u: a=%d, b=%d, c=%d\n",
i, my_array[i].a, my_array[i].b, my_array[i].c);
return 0;
}尽管添加gcc -ansi -Wall标志将引发一些警告,说明ISO C90禁止指定子对象来初始化,但它可以在编译时不使用-pedantic警告或错误。
my_array的初始化将类似于:
MY_INDEX)将包含a=10、b=20、c=30MY_OTHER_INDEX)将有a,b,c= 42我真的很喜欢这种形式的初始化,我觉得它简洁可读的。
在C++中使用这个语法会导致GCC认为我之所以声明lambda函数是因为[],即使没有索引GCC也告诉我它在'struct‘之前预期的主表达式。
什么是C++中的等价物(即使是C++11标准)?关键点能够在初始化器中指定结构字段名以提高可读性(实际结构有十几个整数字段和位字段),也可以在初始化器中看到索引。
发布于 2012-08-21 14:47:50
C++没有C支持的所有特殊聚合初始化器语法。相反,请这样说:
my_struct my_array[] = { { },
{ 10, 20, 30 },
{ 42, 42, 42 },
};数组中不可能有“空白”(我认为在C中也没有)。
https://stackoverflow.com/questions/12057425
复制相似问题