用C实现面向对象

代码:

 1 //This is c program code!                                                                                
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文档信息: *** :~/WORKM/studyCode/gnuC/chapter04/pattarn/testc.c
 4   * 版权声明: *** :(魎魍魅魑)MIT
 5   * 联络信箱: *** :guochaoxxl@163.com
 6   * 创建时间: *** :2020年12月29日的上午08:06
 7   * 文档用途: *** :数据结构与算法分析-c语言描述
 8   * 作者信息: *** :guochaoxxl(http://cnblogs.com/guochaoxxl)
 9   * 修订时间: *** :2020年第52周 12月29日 星期二 上午08:06 (第364天)
10   * 文件描述: *** :自行添加
11  * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/
12 #include <stdio.h>
13 #include <stdlib.h>
14 
15 typedef void (*funSetPtr)(struct _obj *ptrObj, char color);
16 typedef char (*funGetPtr)(struct _obj *ptrObj);
17 typedef void (*funTurnPtr)(struct _obj *ptrObj, char color);
18 
19 typedef struct _obj{
20     char color;
21     funSetPtr set;
22     funGetPtr get;
23     funTurnPtr turn;
24 } Obj;
25 
26 void set(Obj *ptrObj, char color){
27     ptrObj->color = color;
28 
29     return;
30 }
31 
32 char get(Obj *ptrObj){
33     return ptrObj->color;
34 }
35 
36 void turnColor(Obj *ptrObj, char color){
37     if(color == 'g'){
38         if(ptrObj->color == 'g'){
39             printf("The lamp is green, not change!\n");
40         } 
41         if(ptrObj->color == 'r'){
42             printf("The lamp is red, changing...");
43             ptrObj->color = 'g';
44         }
45     }
46     if(color == 'r'){
47         if(ptrObj->color == 'r'){
48             printf("The lamp is red, not change!\n");
49         } 
50         if(ptrObj->color == 'g'){
51             printf("The lamp is green, changing...");
52             ptrObj->color = 'r';
53         }
54     }
55 
56     return;
57 }
58 
59 int main(int argc, char **argv)
60 {
61     Obj *obj = (Obj *)malloc(sizeof(Obj));
62     obj->set = set;
63     obj->get = get;
64     obj->turn = turnColor;
65 
66     obj->set(obj, 'r');
67     printf("the obj color: %c\n", obj->get(obj));
68     obj->turn(obj, 'g');
69 
70     return 0;
71 }

 

posted @ 2020-12-29 17:15  叕叒双又  阅读(385)  评论(0编辑  收藏  举报