【问题标题】:Declaring object classes in C?在 C 中声明对象类?
【发布时间】:2023-02-04 23:17:49
【问题描述】:

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

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,但我想尽可能避免使用 malloc。
有没有一种方便的方法可以在不分配 geometric_object 的情况下到达我想要的位置?

【问题讨论】:

  • 您可以使用union

标签: c object-oriented-analysis


【解决方案1】:

类型将包含两个双打和一个几何图形。

考虑带有标识符的 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);

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多