编辑:感谢您的回复。为开关添加中断;问题确实是我希望能够在 switch 语句之后使用结构。
我希望能够执行以下操作:
int foo (int type, void* inVar) {
switch(type) {
case 0:
struct struct-type-one mystruct = *( (struct struct-type-one*) inVar);
break;
case 1:
struct struct-type-two mystruct = *( (struct struct-type-two*) inVar);
break;
case 2:
struct struct-type-three mystruct = *( (struct struct-type-three*) inVar);
break;
}
// use mystruct.data
}
基本上,inVar
是一个指向结构的指针,type
告诉我们需要什么类型。结构体都有数据,但结构体的类型决定了数据的类型。我想这样做是因为在切换之后的代码中,我们可以对 mystruct.data
进行操作,而不必担心数据实际是什么类型。
我的问题是,我们如何才能做到这一点?例如,这在 Python 中很容易,但 C++ 不喜欢 mystruct
是如何“交叉初始化”的,即根据使用 switch 语句的哪个分支可以有不同的类型。模板化是我们一直在努力解决的一个想法,但这很困难,因为结构的名称不同——例如struct intStruct
,struct floatStruct
。这很重要,因为这些结构的大小取决于数据类型。有什么想法吗?
最佳答案
我不相信可以直接 做您想做的事(即使是,它也是 C/C++ 中的反模式)。但是,如果您想使用 mystruct.data
(而不是 mystruct
本身),那么您可以这样重写代码:
int foo (int type, void* inVar) {
void* mystruct_data = NULL;
switch(type) {
case 0:
mystruct_data = ((struct struct-type-one*) inVar)->data;
break;
case 1:
mystruct_data = ((struct struct-type-two*) inVar)->data;
break;
case 2:
mystruct_data = ((struct struct-type-three*)inVar)->data;
break;
}
// use mystruct_data (and don't forget to check it's not NULL)
}
请注意,您需要先声明变量——无论您在 switch()
中声明什么,其作用域都仅限于该 switch()
。
或者,如果您的数据处理依赖于类型
,您可以这样做:
int foo (int type, void* inVar) {
switch(type) {
case 0:
data_process_1((struct struct-type-one*) inVar);
break;
case 1:
data_process_2((struct struct-type-two*) inVar);
break;
case 2:
data_process_3((struct struct-type-three*) inVar);
break;
}
}
关于C++决定开关中变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842388/