許多朋友都知道用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([email protected]) 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 interface(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等對象是如何描述的呢,請看下集分解。