我对以下 C++ 代码有疑问:
typedef struct {
int id;
int age;
} Group1;
typedef struct {
int id;
char name;
float time;
} Group2;
typedef union {
Group1 group1;
Group2 group2;
} ServiceData;
typedef struct {
ServiceData data;
} Time;
然后我有一个变量:
Group1 * group1;
group1 = new Group1;
group1->id = 10;
group1->age = 20;
然后有两个这样定义的方法:
void method1(ServiceData * data) {
//inside the method call method hello
hello(data);
};
void hello(Group1 *group1) {
printf("%d",group1->id);
}
我这样调用 method1
:
method1((ServiceData *)group1);
但是在method1
里面,当参数group1
传给方法hello()
的时候,我想获取id里面的值组 1
。我需要在 hello
方法中做任何转换吗?或者在 method1
内部,我是否需要在将其传递给 hello()
之前将其转换为 (group*)
?
最佳答案
您不需要强制转换,只需访问 union
中的正确字段:
void method1(ServiceData * data) {
//inside the method call method hello
hello(&data->group1);
};
关于c++ - 访问 union 成员需要类型转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12087679/