我对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));
}