上集对OOSM宏包及其应用作了直观的介绍,下面我们来看看ccirc/crect/csqua等对象具体的描述方式。
接口(interface)对行为进行抽象,利用它可以实现类的多态性,imeas.h定义了一个测量周长和面积的接口:
#ifndef __IMEAS_H__
#define __IMEAS_H__
#include "oosm.h"
/* Measuring Interface, for measuring the perimeter and area of objects */
interface(imeas)
{
double (*peri)(void* this); /* for measuring the perimeter of objects */
double (*area)(void* this); /* for measuring the area of objects */
};
#endif/*__IMEAS_H__*/
由于接口是抽象的,所以特别注意把this指针声明为void*类型,这样在进行指针转换的时候会比较方便。
类(class)拥有属性和方法,多态方法采用实现接口的方式来达成目的,crect.h/crect.c定义和实现了一个矩形类:
#ifndef __CRECT_H__
#define __CRECT_H__
#include "imeas.h"
/* Rectangle Class, for describing rectangle objects */
class(crect)
{
implements(imeas); /* Implements imeas interface */
double width;
double height;
};
#endif/*__CRECT_H__*/
#incl

本文继续探讨C语言实现面向对象程序设计,重点解析ccirc/crect/csqua对象的描述方式。通过接口interface实现行为抽象和多态性,如imeas.h中定义的测量接口。接着,文章介绍了crect.h/crect.c中矩形类的构造与析构,以及如何映射和实现imeas接口的方法。同时,ccir.h/ccir.c展示了圆形类的定义和实现。
最低0.47元/天 解锁文章
2169

被折叠的 条评论
为什么被折叠?



