我在 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" },
...
现在因语法错误而失败。我已经看到了 Statically initialize anonymous union in C++ 的回复但是重载构造函数是行不通的,因为我正在设置一个数组。有没有其他方法可以做到这一点(而不是仅仅重写代码而不是使用 union )?
更新: 我应该更具体一些——数组包含使用 union 所有部分的不同初始化器:
static int is_full_screen;
{ "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
所以仅仅改变并集的顺序是无济于事的。
最佳答案
C++ 没有 C 所具有的 .member
初始化语法。
您可以对 union 使用聚合初始化,但仅限于第一个成员。
因此,用你想设置为第一个成员的那个重写它:
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) };
关于c++ - 如何静态初始化包含 union 的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638349/