OOPC实现

       OOP(Object Oriented Programming) 为面向对象编程,OOPC为用C语言实现面向对象编程,虽然没有别的面向对象语言那么齐备全面,但却给人以一窥究竟的感觉,挺有意思。    
       在看《UML+OOPC嵌入式C语言开发精讲》时,觉得里面对OOP的实现挺有意思,记录如下:

/* lw_oopc.h */		/*这就是MISOO团队所设计的C宏*/
#include 
#ifndef LOOPC_H
#define LOPPC_H

#define CLASS(type) \
typedef struct type type; \
struct type

#define CTOR(type) \
void* type##New() \
{ \
	struct type *t; \
	t = (struct type *)malloc(sizeof(struct type)); 

#define CTOR2(type, type2) \
void* type2##New() \
{ \
	struct type *t; \
	t = (struct type *)malloc(sizeof(struct type)); 

#define END_CTOR	return (void*)t; }
#define FUNCTION_SETTING(f1, f2) t->f1 = f2;
#define IMPLEMENTS(type) struct type type
#define INTERFACE(type) struct type
#endif
/*	end		*/

注:在第一章中的lw_oopc.h文件存在问题,详见10.5.2中lw_oopc.h的定义。

type##New为将type变量和New连接起来,如type为Light时,则type##New为LightNew  

下面为lw_oopc.h的具体应用:

/*light.h*/
#include "lw_oopc.h"

CLASS(Light)
{
	void (*turnon)();
	void (*turnoff)();
};
/*light.c*/
#include 
#include "light.h"

static void turnOn()
{
	printf("Light is ON\n");
}

static void turnOff()
{
	printf("Light is OFF\n");
}

CTOR(Light)
	FUNCTION_SETTING(turnon, turnOn)
	FUNCTION_SETTING(turnoff, turnOff)
END_CTOR
/*main.c*/
#include "stdio.h"
#include "lw_oopc.h"
#include "light.h"

extern void* LightNew();
void main()
{
	Light *light = (Light *)LightNew();
	light->turnon();
	light->turnoff();
	return;
}

预处理后的文件为:

/*light.h*/
# 3 "lw_oopc.h" 2
# 3 "light.h" 2

typedef struct Light Light; struct Light   /*CLASS(type)*/
{
 void (*turnon)();
 void (*turnoff)();
};

/*light.c*/
static void turnOn()
{
 printf("Light is ON\n");
}

static void turnOff()
{
 printf("Light is OFF\n");
}

void* LightNew() { struct Light *t; t = (struct Light *)malloc(sizeof(struct Light));   /*CTOR(Light)*/
 t->turnon = turnOn;                  /*FUNCTION_SETTING(turnon, turnOn)*/
 t->turnoff = turnOff;                /*FUNCTION_SETTING(turnoff, turnOff)*/
return (void*)t; }                    /*END_CTOR*/
/*main.c*/
extern void* LightNew();              /*void* type##New()*/
void main()
{
 Light *light = (Light *)LightNew();
 light->turnon();
 light->turnoff();
 return;
}

你可能感兴趣的:(笔记)