c++ - 访问 union 成员需要类型转换吗?

标签 c++ casting struct unions

我对以下 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/

相关文章:

c++ - 如何将 vector 列表存储为全局变量?

c++ - 解码 H264/RTSP 流后未设置 PTS

c++ - ((MPI_Datatype)1) 在 C++ 中是什么意思?

c++ - 是否有任何可移植的方法来确保在不使用 c++11 填充字节的情况下定义结构?

asp.net-mvc - asp.net mvc3 razor 语法通过反射将模型转换为其子类

C# 通过对象拆箱

c++ - 递归算法和指针的问题

c - 从 C 中的结构数组中检索结构以进行 qsort

c++ - 传递给 qt 插件的对象的调用方法产生符号查找错误

c++ - 构造函数的条件调用