用C语言实现面向对象程序设计(三)

来源:互联网 发布:重庆邮电大学人工智能 编辑:程序博客网 时间:2024/06/17 16:55

面向对象中的继承又是如何处理的呢,下面来看看方形类的具体描述方式:

#ifndef __CSQUA_H__#define __CSQUA_H__#include "crect.h"/* Square Class, inherits from Rectangle, for describing square objects */class(csqua){    extends(crect); /* Inherits from crect class */};#endif/*__CSQUA_H__*/

csqua.h中csqua类直接从crect类继承(extends),方形对于矩形来说,是其width和height相等的特例。

#include "csqua.h"static double peri(void* this){    return 4 * ((crect*)this)->width;}static double area(void* this){    return ((crect*)this)->width * ((crect*)this)->width;}constructor(csqua){    mapping(crect.imeas.peri, peri);    mapping(crect.imeas.area, area);}destructor(csqua){    return 1; /* Returns 1 for freeing the memory */}
csqua.c中注意width是矩形的属性,因此this指针实际是crect*型的。

至此,OOSM宏包加上一个简单完整的示例都已经介绍完毕,从这里可以看出面向对象是一种思想,而不是某种语言的专利。当然由于C语言本身是面向过程的,所以它无法实现private/public/protect等界限,也无法隐藏this指针,导致形式上会有c->diam(c)这样比较不自然的写法,另外继承不宜过深。


原创粉丝点击