[英]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: 字段
x
是mainStruct
的直接成员,因此很自然地起作用:
int d = myStruct->x;
The field a
is a member of middleStruct
, which is a variant of u
, which is member of mainStruct
. 字段
a
是middleStruct
的成员, middleStruct
是u
的变体, u
是mainStruct
成员。 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. 因为
x
是mainStruct
的成员,但a
不是。
a
is a member of middleStruct
which is a member of u
which is a member of mainStruct
. a
是middleStruct
的成员,而middleStruct
是u
的成员,而u
是mainStruct
的成员。 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.