在c语言中,模拟多态并不是一件简单的事,笔者简单说一下如何使用c语言模拟多态,该版本为粗糙版本。
shape.h:
typedef struct {
void (*draw)();
} Shape;
circle.h:
typedef struct {
Shape base;
} thecircle;
thecircle* newcircle();
circle.c:
void ciprit() {
printf("this is a circle!\n");
}
thecircle* newcircle() {
thecircle* t_circle = (thecircle*) malloc(sizeof(thecircle));
t_circlet->base.draw = ciprit;
return t_circle;
}
在main函数中直接这样调用:
int main() {
Shape* shape1 = (Shape*) newcircle();
shape1->speak();
free(shape1);
return 0;
通过这种方法,就可以实现多态。