【发布时间】:2016-05-04 07:55:16
【问题描述】:
我有一个结构,其中包含一个可以采用多种类型的属性, 我想问一下声明这个属性的最合适的方式。
例子:
struct
{
void* pShape; //poiter to the shape that will be casted on *tCircle or *tRectangle
int type;//type of the shape
int h;
int l;
}tImage;
struct{
int size;
int r;
HANDLE calcul;
}tCircle
struct{
int size;
int x;
int y;
HANDLE calcul;
}tRectangle;
正如你在这里看到的,我使用 void* 来声明指向形状的指针并使用 type 属性来猜测形状的类型。
这是我计算图像中形状大小的函数
int Image_Get_ShapeSize(tImage Im)
{
switch (Im.type)
{
case CIRCLE:
((tCircle*)(Im.shape))->calcul();
break;
case RECTANGLE:
((tRectangle*)(Im.shape))->calcul();
break;
default:
break;
}
}
你觉得这是一个好方法吗?
【问题讨论】:
-
HANDLE是如何定义的? -
我建议为所有形状创建特定的函数。
-
@bzeaman 是的,确实,在初始化 tCircle 或 tRectangle 类型的变量时,属性计算将指向不同的函数
标签: c struct void-pointers