【问题标题】:Declaring struct attribute with different type声明具有不同类型的结构属性
【发布时间】: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 是如何定义的?
  • 我建议为所有形状创建特定的函数。
  • C struct to void* pointer的可能重复
  • @bzeaman 是的,确实,在初始化 tCircle 或 tRectangle 类型的变量时,属性计算将指向不同的函数

标签: c struct void-pointers


【解决方案1】:

我不太明白为什么需要 tCircle 和 tRectangle 结构,因为它们具有相同的字段。我建议您只使用一个定义并将函数指针初始化为不同的特定方法。

struct shape {
    int size;
    int x;
    int y;

    void (*calcul) (struct shape * shape);
};

然后是具体功能:

void circle_calcul(struct shape * shape)
{
    ...
}

void rectangle_calcul(struct shape * shape)
{
    ...
}

最后:

struct shape circle;
struct shape rectangle;

circle.calcul = circle_calcul;
rectangle.calcul = rectangle_calcul;

【讨论】:

  • 好话我更新了结构的声明。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多