2012-11-30 67 views
1

我在Visual Studio 2010中移植一些舊的代碼,從C到C++,我碰到這個傳來:如何靜態初始化一個包含union的結構數組?

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++的響應,但重載構造函數將不起作用,因爲我正在設置一個數組。有沒有其他的方式來做到這一點(而不是隻是重寫代碼不使用聯合)?

更新: 我本來應該更具體的 - 數組包含使用工會各地不同initialisers:

static int is_full_screen; 

    { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" }, 

所以只是改變了工會的順序也無濟於事。

+0

不幸的是,得心應手C99語法*指定初始化*沒使它成爲C + + 11 :( – dasblinkenlight

回答

1

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) }; 
+0

第一個想法不起作用,請參閱我更新的問題。但我可以在數組中使用構造函數嗎?我不認爲這是可能的。 – parsley72

+0

@ parsley72是的,你可以。我更新了一些例子。 – Pubby

-1

只是這樣做:

static const OptionDef options[] = { 
    { "x", HAS_ARG, {opt_width }, "force displayed width", "width" }, 
    ... 
+0

這將工作沒有重新排序的聯盟?我認爲只有第一個成員被設置。 – parsley72

+0

聯盟只是一個內存塊與它的元素最大的大小如何解釋存儲在內存中的數據取決於你的代碼。例如,你設置{0}爲聯合,我如果你的代碼是「u.dst_ptr」,那麼「0」是dst_ptr的NULL;如果你的代碼是「u.func_arg」,那麼「0」是NULL函數指針;如果你的代碼是「u.off」,那麼「0」表示off var是0.這就是union和struc之間的區別。 – TieDad