简体   繁体   English

直接访问结构中的联合

[英]Directly accessing a union within a struct

Let's say I have the following tagged union:假设我有以下标记的联合:

typedef struct Form {
    FormType type;
    union {
        TaxForm tax; 
        BusinessForm bus; 
    } u;
} Form;

To access the main/sub object I have to do:要访问主/子 object 我必须这样做:

form->u.bus表单->u.bus

Is there a way to either do:有没有办法做到:

form->u

Or:或者:

form->bus

That is, to be able to access union object directly without going through its declarator (since by definition, the union will only have one item set).也就是说,能够直接访问联合 object 而无需通过其声明符(因为根据定义,联合将只有一个项目集)。

You can only do this by omitting the u from the original definition:您只能通过从原始定义中省略u来做到这一点:

typedef struct Form {
    FormType type;
    union {
        TaxForm tax; 
        BusinessForm bus; 
    };  // <--- no u
} Form;

Then you can use form->bus and so on, where form is a pointer to Form .然后你可以使用form->bus等等,其中form是一个指向Form的指针。

This is called "anonymous unions" and was added in the C11 standard revision, so you will need to invoke your compiler in C11 or later mode, or hope that it supported this as an extension in older modes.这被称为“匿名联合”,是在 C11 标准修订版中添加的,因此您需要在 C11 或更高版本的模式下调用编译器,或者希望它作为旧模式的扩展支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM