用C语言声明对象类?

x33g5p2x  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(113)

我声明了一些几何图形类型,例如:

typedef struct s_sphere{
    t_tuple origin;
    double  radius;
} t_sphere;

typedef struct s_cylinder{
    t_tuple origin;
    double  height;
    double  radius;
} t_cylinder;

typedef struct s_triangle{
    t_tuple A;
    t_tuple B;
    t_tuple C;
} t_triangle;

etc...

现在,我想要声明一个交集类型,它包含两个双精度数和一个几何图形,然后我将把所有交集存储在一个链表中:

// I do not know what type to give to geometric_figure
typedef struct  s_intersection{
    double       t1;
    double       t2;
//  what_type    geometric_figure;
} t_intersection;

typedef struct  s_intersection_list{
    t_intersection              intersection;
    struct s_intersection_list  *next;
} t_intersection_list;

我可以使用void* geometric_figure,但我希望尽可能避免最多的mallocs。
有没有一种简便的方法可以在不分配geometric_object的情况下到达我想要的位置?

x9ybnkn6

x9ybnkn61#

类型,它将包含两个双精度和一个几何图形。
考虑带有标识符的union

typedef struct  s_intersection{
  double       t1;
  double       t2;
  int id;  // some id to know what type follows
  union {
    t_sphere sph;
    t_cylinder cyl;
    t_triangle tri;
  } u;
} t_intersection;

如果要分配t_intersection,请考虑使用flexible member array来正确调整分配大小。

typedef struct  s_intersection{
  double       t1;
  double       t2;
  int id;  // some id to know what type follows
  union {
    t_sphere sph;
    t_cylinder cyl;
    t_triangle tri;
  } u[];   // FAM
} t_intersection;

示例:分配一个三角形。

t_intersection *p = malloc(sizeof *p + sizeof p->u[0].tri);

相关问题