简体   繁体   English

C ++在并集结构中访问变量

[英]C++ accessing a variable in a union struct

I am working with a library who has a struct defined as such: 我正在与一个结构定义如下的图书馆合作:

typedef struct {
    int x;
    union {
        struct {
            y;
            union {
                int z;
            } innerStruct;
            char *a;
        } middleStruct;
    int q;
    } u;
} mainStruct;

How do I access char* a? 如何访问char * a?

I have tried multiple methods. 我尝试了多种方法。 This works: 这有效:

mainStruct *myStruct;
int d = myStruct->x;

But this does not work: 但这不起作用:

char *d = myStruct->a;

I can get x fine using the above method but not a. 我可以使用上述方法获得x的罚款,但不能。 why? 为什么?

I have never worked with unions before and I am forced to use this struct as part of the library I need. 我以前从未与工会合作过,我被迫将此结构用作我需要的库的一部分。 Thanks for the help in advance and sorry if I am butchering this question. 感谢您的提前帮助,如果我提出这个问题,对不起。

The field x is a direct member of mainStruct , so it's natural that this works: 字段xmainStruct的直接成员,因此很自然地起作用:

int d = myStruct->x;

The field a is a member of middleStruct , which is a variant of u , which is member of mainStruct . 字段amiddleStruct的成员, middleStructu的变体, umainStruct成员。 It's more deeply nested than x , so you need to navigate the data structure like this: 它比x嵌套得更深,因此您需要像这样导航数据结构:

char *d = myStruct->u.middleStruct.a;

I can get x fine using the above method but not a. 我可以使用上述方法获得x的罚款,但不能。 why? 为什么?

Because x is a member of mainStruct , but a isn't. 因为xmainStruct的成员,但a不是。

a is a member of middleStruct which is a member of u which is a member of mainStruct . amiddleStruct的成员,而middleStructu的成员,而umainStruct的成员。 You can access members of union instances using the same syntax as you access members of non-union class instances. 您可以使用与访问非工会类实例的成员相同的语法来访问工会实例的成员。 So, you can write myStruct->u.middleStruct.a 因此,您可以编写myStruct->u.middleStruct.a

PS The behaviour of mainStruct->u is undefined unless you first initialize mainStruct . PS除非首先初始化mainStruct否则mainStruct->u的行为是不确定的。

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

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