p, 10, 20);
draw(p);
cdelete(p);
}
return 0;
}
/***********************************
* 测试结果:
*
* Point_New self = 0x50a1d8
* call Circle_New self =0x50a1d8
* Circle_Draw at 1,2 rad 3
* call move self =0x50a1d8
* Circle_Draw at 11,22 rad 3
* call Circle_Delete self =0x50a1d8
*
* Point_New self = 0x5096a0
* Point_Draw at 1,2
* call move self =0x5096a0
* Point_Draw at 11,22
* call Point_Delete self =0x5096a0
*
************************************/
五、多态
可以是用C语言中的万能指针void* 实现多态,接上面的例子:
//测试main.c
int oo_main(int argc, char ** argv) {
void * p;
int i;
for (i = 0; i < 2; i++) {
if (i == 0) {
p = cnew(Circle, 1, 2, 3);
circle_area(p);
} else {
p = cnew(Point, 1, 2);
}
draw(p);
move(p, 10, 20);
draw(p);
cdelete(p);
}
return 0;
}
六、总结
C语言能够模拟实现面向对象语言具有的特性,包括:多态,继承,封装等,现在很多开源软件都了用C语言实现了这几个特性,包括大型开源
数据库
系统postgreSQL,可移植的C语言面向对象框架GObject,无线二进制运行环境BREW。采用C语言实现多态,继承,封装,能够让软件有更好的可读性,可扩展性。
?
?
|