用C實現面向物件
阿新 • • 發佈:2020-12-29
程式碼:
1 //This is c program code! 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= 3 * 文件資訊: *** :~/WORKM/studyCode/gnuC/chapter04/pattarn/testc.c 4 * 版權宣告: *** :(魎魍魅魑)MIT 5 * 聯絡信箱: *** :[email protected] 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, charcolor); 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 }