如何静态初始化包含联合的结构数组? 我在Visual Studio 2010中移植了一些C到C++的旧代码,我发现了: typedef struct OptionDef { const char *name; int flags; union { void *dst_ptr; int (*func_arg)(void *, const char *, const char *); size_t off; } u; const char *help; const char *argname; } OptionDef; static const OptionDef options[] = { { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" }, ...

如何静态初始化包含联合的结构数组? 我在Visual Studio 2010中移植了一些C到C++的旧代码,我发现了: typedef struct OptionDef { const char *name; int flags; union { void *dst_ptr; int (*func_arg)(void *, const char *, const char *); size_t off; } u; const char *help; const char *argname; } OptionDef; static const OptionDef options[] = { { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" }, ...,c++,arrays,visual-studio-2010,initialization,unions,C++,Arrays,Visual Studio 2010,Initialization,Unions,现在由于语法错误而失败。我已经看到了的响应,但是重载构造函数将不起作用,因为我正在设置数组。除了重写代码而不使用联合,还有其他方法可以做到这一点吗 更新: 我应该说得更具体一些-数组包含使用联合体所有部分的不同初始值设定项: static int is_full_screen; { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" }, 因此,仅仅改变工会的顺序是没有帮助的。只要这样做: static const

现在由于语法错误而失败。我已经看到了的响应,但是重载构造函数将不起作用,因为我正在设置数组。除了重写代码而不使用联合,还有其他方法可以做到这一点吗

更新: 我应该说得更具体一些-数组包含使用联合体所有部分的不同初始值设定项:

static int is_full_screen;

    { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
因此,仅仅改变工会的顺序是没有帮助的。

只要这样做:

static const OptionDef options[] = {
   { "x", HAS_ARG, {opt_width }, "force displayed width", "width" },
    ...
C++没有C所具有的.member初始化语法

可以对联合使用聚合初始化,但只能对第一个成员使用聚合初始化

因此,请使用要设置为第一个成员的成员重写它:

union {
    int (*func_arg)(void *, const char *, const char *);
    void *dst_ptr;
    size_t off;
} u;

static const OptionDef options[] = {
    { "x", HAS_ARG, { opt_width }, "force displayed width", "width" },
您还可以给结构一个构造函数-C++11应该允许您使用括号初始值设定项

例如:

struct foo {
    int flags;
    struct uwrap {
      uwrap(int (*func_arg)(void *, const char *, const char *))
      : func_arg(func_arg) {}
      uwrap(int off)
      : off(off) {}
      union {
          void *dst_ptr;
          int (*func_arg)(void *, const char *, const char *);
          int off;
      };
    } u;
};

int func(void *, const char *, const char *) {}

int main() {
    foo f[] = { { 1, {func}}, { 2, {0}} };
}
在C++03中,如果结构具有构造函数,则可以使用临时结构:

foo f[] = { foo(1, func), foo(3, 0) };

不幸的是,用于指定初始值设定项的方便的C99语法没有进入C++11:第一个想法行不通,请参阅我的更新问题。但是我可以在数组中使用构造函数吗?我认为这是不可能的。如果不重新安排工会,这行得通吗?我以为只设置了第一个成员。联合只是一块内存块,其元素的大小最大。如何解释存储在内存中的数据取决于您的代码。例如,将{0}设置为并集,如果代码为u.dst_ptr,则0为dst_ptr的NULL;如果代码为u.func_arg,则0为空函数指针;如果代码为u.off,则0表示off变量为0。这就是union和struc的区别。