在c语言中,模拟多态并不是一件简单的事,笔者简单说一下如何使用c语言模拟多态,该版本为粗糙版本。
1 2 3 4 5
| shape.h:
typedef struct { void (*draw)(); } Shape;
|
1 2 3 4 5 6 7 8
| circle.h:
typedef struct { Shape base; } thecircle;
thecircle* newcircle();
|
1 2 3 4 5 6 7 8 9 10 11
| 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函数中直接这样调用:
1 2 3 4 5 6 7 8 9
| int main() {
Shape* shape1 = (Shape*) newcircle();
shape1->speak();
free(shape1);
return 0;
|
通过这种方法,就可以实现多态。