我在某处读到关于如何在C语言中实现一些面向对象的特性,这已经被证明非常有用。具体来说,我一直在考虑继承的概念。以下是一个示例:
typedef struct Circle{
int rad, x, y;
//Other things...
} Circle;
typedef struct Entity{
Circle body;
//Entity-specific items...
} Entity;
这很简单,但它允许一些巧妙的操作。指向实体的指针也是指向圆形的指针,因为实体的第一个元素始终是一个圆形。基于这个想法,我们可以构造出以下函数:
int checkCircleCollision(Circle* one, Circle* two);
并将其称为:
Entity* myentity = createEntity(/* Things specific to my entity */);
Entity* myotherentity = createEntity(/* Different things */);
//Did they collide?
if (checkCircleCollision(myentity, myotherentity)){
/* ... */
}
这很棒,但我遇到了一个问题。如果我也想让我的实体成为矩形怎么办?我有一个解决方案,但我想确认它是否总是有效,无论编译器如何。我的联合知识非常有限。
//Circle defined as above...
typedef struct Rectangle{
int x, y, w, h;
//Other things...
} Rectangle;
int checkRectangleCollision(Rectangle* one, Rectangle* two);
int checkRectangleCircleCollision(Rectangle* rect, Circle* circ);
typedef struct Entity{
union{
Rectangle rect;
Circle circ;
} shape;
int type;
//Entity things...
}
现在可以完全安全地假设一个实体(Entity
)的第一个元素是根据其初始化是Rectangle
或Circle
中的一个吗?此外,它是否可以用于上述三个函数中的任何一个?如果有相关标准的引用,则额外加分。为了更清楚地表达,我希望这样做:
Entity* rectentity = createEntity(RECTANGLE, /* width/height/etc */);
Entity* circentity = createEntity(CIRCLE, /* rad/x/y/etc */ );
if (checkRectangleCircleCollision(rectentity, circentity)){
/* ... */
}
Circle
占用 4 个 int 的空间,尽管它只使用了 3 个)。 - el.pescado - нет войне