1 /************************************************************************/
2 /* object 基类 */
3 /************************************************************************/
4
5
6 typedef struct stObj OBJECT_STRU;
7
8 typedef char* (*ToString_PF)(void *pObj, char *pcStrBuf);
9 typedef unsigned int ClassID;
10
11 struct stObj
12 {
13 ClassID m_uiCID;
14 ToString_PF pfToString;
15 };
16
17 char* OBJ_ToString(void *pObj, char *pcStrBuf)
18 {
19 sprintf(pcStrBuf, "ClassName:%s;ClassID:%06u", "Object", ((OBJECT_STRU *)pObj)->m_uiCID);
20 return pcStrBuf;
21 }
22
23 OBJECT_STRU *new_Object()
24 {
25 OBJECT_STRU* pstObj = (OBJECT_STRU*)malloc(sizeof(OBJECT_STRU));
26
27 if ( NULL == pstObj )
28 {
29 return NULL;
30 }
31
32 pstObj->m_uiCID = CID_OBJ;
33 pstObj->pfToString = OBJ_ToString;
34
35 return pstObj;
1 ==========
2
3 /************************************************************************/
4 /* 测试 */
5 /************************************************************************/
6
7 int main()
8 {
9 char acStrBuf[200] = {0};
10
11 OBJECT_STRU *pObj = NULL;
12 ANIMAL_STRU *pAnm = NULL;
13 PLANT_STRU *pPlt = NULL;
14
15 // 定义父类
16 OBJECT_STRU *pObj_animal = NULL;
17 OBJECT_STRU *pObj_plant = NULL;
18
19 // 父类函数和属性调用
20 pObj = new_Object();
21 printf("[ID = %u][ ToString = %s ]\n", pObj->m_uiCID, pObj->pfToString(pObj, acStrBuf) );
22 free(pObj);
23 pObj = NULL;
24
25 // 子类函数和属性调用
26 pAnm = new_Animal();
27 strcpy(pAnm->acName,"Panda");
28 printf("%s\n", pAnm->m_stBaseObj.pfToString(pAnm, acStrBuf) );
29 free(pPlt);
30 free(pAnm);
31 pPlt = NULL;
32 pAnm = NULL;
33
34 // 子类函数和属性调用
35 pPlt = new_Plant();
36 strcpy(pPlt->acName,"Tree");
37 printf("%s\n", pPlt->m_stBaseObj.pfToString(pPlt, acStrBuf) );
38
39
40 /************************************************************************/
41 /* 多态测试 */
42 /************************************************************************/
43
44 // 定义父类
45 // OBJECT_STRU *pObj_animal = NULL;
46 // OBJECT_STRU *pObj_plant = NULL;
47
48 // 初始化子类
49 pObj_animal = (OBJECT_STRU *)new_Animal();
50 pObj_plant = (OBJECT_STRU *)new_Plant();
51
52 // 执行相同的函数产生不同的效果
53 printf("%s\n", pObj_animal->pfToString(pObj_animal, acStrBuf) );
54 printf("%s\n", pObj_plant->pfToString(pObj_plant , acStrBuf) );
55
56 getchar();
57
58 free(pObj_animal);
59 free(pObj_plant );
60
61 return 0;
62 }
63