2

我一直在浏览有关在结构中初始化联合的问题的 stackoverflow,但我没能做到正确。

这是我的结构

typedef struct dc_netif_filter {
    unsigned char filter_type;  
    union {
        uint32_t itf_nb;
        char * buf; 
    } value;
} dc_netif_filter_t;  

在我的代码中,我尝试使用:

dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,{{0, "tun"}}};  

这给出了错误:用于类型“uint32_t”的标量初始值设定项的大括号</p>

dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,{0, "tun"}};  

这给出了错误:'dc_netif_filter::<匿名联合>'的初始化程序太多</p>

我如何声明这样的 dc_netif_filter_t ?

我在 ubuntu 上使用 g++。请注意,dc_netif_filter_t 不是我可以修改的结构,因为它来自第三方项目。

**编辑:正如我已经解释过的,我只能初始化一个字段。问题是,与

dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,"tun0"}; 

我收到一个转换错误:从 'const char*' 到 'uint32_t 的无效转换

谢谢

4

3 回答 3

6
于 2012-04-16T13:24:12.850 回答
2

It looks like you are trying to initialize your structure to indicate that the buf member is to be used, and that the value of that buf should be "tun". Since C++ before C++11 lacks designated initializers, you cannot do it with an initializer: only the first field of the union can be initialized, so you need to do your assignment in code:

static get_dc_netif_filter_t() {
    static c_netif_filter_t netif = {DC_NETIF_SELECT_NAME, {0}};
    if (netif.value.itf_nb == 0) {
        netif.value.buf = "tun";
    }
    return netif;
}

C++11 lets you do it like this:

dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME, { .buf = "tun"}};
于 2012-04-16T13:34:40.537 回答
1

This works under g++ 4.7.0:

dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME, {.buf="tun"}};

Although designated initializers are supposed to be C only, not C++! Maybe it's a GNU extension?

I guess the best (most compatible) way is to assign the members after initialization:

dc_netif_filter_t netif;
netif.itf_nb = DC_NETIF_SELECT_NAME;
netif.value.buf = "TUN";
于 2012-04-16T13:34:24.420 回答