访问联合成员需要类型转换
Type cast required for access to union member?
我对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()
时,我想得到group1
内部id的值。我需要在hello
方法中进行任何转换吗?或者在method1
内部,在将其传递给hello()
之前,是否需要将其强制转换为(group*)
?
您不需要强制转换,只需要访问union
:中的正确字段
void method1(ServiceData * data) {
//inside the method call method hello
hello(&data->group1);
};
而不是
method1((ServiceData *)group1);
你应该这样做:
ServiceData data;
data.group1.id = 10;
data.group1.age = 20;
method1(data);
method1
的实现应该看起来像
void method1(ServiceData * data) {
hello(&data->group1);
};
当然,您必须编写
hello ( (Group1 * ) data);
(或写入数据->组1,其他答案)。
但不要这样做,而是使用继承,如果是C++:
struct GroupBase {
int id;
virtual ~GroupBase {
}
}
struct Group1 : public GroupBase {
int age;
virtual ~Group1 { }
}
struct Group2 : public GroupBase {
char name;
float time;
virtual ~Group2 { }
}
void method1 (GroupBase* data) {
hello (std::dynamic_cast<Group1*> (data));
}
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 在 C++ 中用派生类型重写成员函数
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 指针类型类成员的动态强制转换的恒定性是什么?
- 指向类成员函数的指针中存在类型转换错误
- 如何类型转换为模板成员函数参数?
- 访问联合成员需要类型转换
- 如何使用基类指针调用派生类非虚拟成员函数,而无需类型转换和使用多态性
- 不能在类型转换为void *的对象上调用成员函数指针
- 使用指针成员对结构体进行类型转换