许多朋友都知道用C语言是可以实现面向对象程序设计的,但是具体到操作的细节部分就有些茫然不知所措了。为此作者在研究LW_OOPC的基础上,对其进行充分的简化,只保留最基本的面向对象功能,形成自己的OOSM宏包,其实这些东西已经够用了,以下是OOSM宏包的源代码:
[cpp]
/*
Object-Oriented Support Macros(OOSM)
OOSM is an object-oriented support macros, it makes the C programming language
with object-oriented programming capabilities.
LW_OOPC(http://sourceforge.net/projects/lwoopc/) means
Light-weight Object-Oriented Programming in C, written by MISOO team,
it is a very outstanding works!
OOSM inherits the essence of LW_OOPC and crops to retain the basic features.
OOSM written by Turingo Studio,
but anyone can copies modifies, and distributes it freely.
Hansome Sun(hansome.sun@gmail.com)
January 18, 2013
*/
#ifndef __OOSM_H__
#define __OOSM_H__
#include <stdlib.h>
#define class(type) \
typedef struct type type; \
type* type##_new(void); \
void type##_constructor(type* t); \
int type##_destructor(type* t); \
void type##_delete(type* t); \
struct type
#define inte易做图ce(type) \
typedef struct type type; \
struct type
#define extends(type) type type
#define implements(type) type type
#define constructor(type) \
type* type##_new(void) \
{ \
type* this; \
this = (type*)malloc(sizeof(type)); \
if(this == NULL) return NULL; \
type##_constructor(this); \
return this; \
} \
\
void type##_constructor(type* this)
#define destructor(type) \
void type##_delete(type* this) \
{ \
if(type##_destructor(this)) free(this); \
} \
\
int type##_destructor(type* this)
#define mapping(tf, sf) this->tf = sf
#endif/*__OOSM_H__*/
真正的代码不到30行,大家可以直观的意识到用C语言实现面向对象的代价其实是非常低的。在OOSM宏包的支持下,C语言的代码可以如此的优雅紧凑:
[cpp]
#include <stdio.h>
#include "imeas.h"
#include "ccirc.h"
#include "crect.h"
#include "csqua.h"
int main(int argc, char* argv[])
{
ccirc* c = ccirc_new();
crect* r = crect_new();
csqua* s = csqua_new();
c->radius = 9.23;
r->width = 23.09;
r->height = 78.54;
s->crect.width = 200.00;
printf("Circle: (%lf, %lf, %lf)\n", c->diam(c), c->imeas.peri(c), c->imeas.area(c));
printf("Rectangle: (%lf, %lf)\n", r->imeas.peri(r), r->imeas.area(r));
printf("Square: (%lf, %lf)\n", s->crect.imeas.peri(s), s->crect.imeas.area(s));
ccirc_delete(c);
crect_delete(r);
csqua_delete(s);
return 0;
}
那么ccirc/crect/csqua等对象是如何描述的呢,请看下集分解。