test.h #ifndef _TEST_H_ #define _TEST_H_ typedef void Demo; typedef void Derived; Demo* Demo_Create(int i, int j); int Demo_GetI(Demo* pThis); int Demo_GetJ(Demo* pThis); int Demo_Add(Demo* pThis, int value); void Demo_Free(Demo* pThis); Derived* Derived_Create(int i, int j, int k); int Derived_GetK(Derived* pThis); int Derived_Add(Derived* pThis, int value); #endif test.c #include "test.h" #include "malloc.h" static int Demo_Virtual_Add(Demo* pThis, int value); static int Derived_Virtual_Add(Demo* pThis, int value); struct VTable // 2. 定义虚函数表数据结构 { int (*pAdd)(void*, int); // 3. 虚函数表里面存储什么??? }; struct ClassDemo { struct VTable* vptr; // 1. 定义虚函数表指针 ==》 虚函数表指针类型??? int mi; int mj; }; struct ClassDerived { struct ClassDemo d; int mk; }; static struct VTable g_Demo_vtbl = { Demo_Virtual_Add }; static struct VTable g_Derived_vtbl = { Derived_Virtual_Add }; Demo* Demo_Create(int i, int j) { struct ClassDemo* ret = (struct ClassDemo*)malloc(sizeof(struct ClassDemo)); if( ret != NULL ) { ret->vptr = &g_Demo_vtbl; // 4. 关联对象和虚函数表 ret->mi = i; ret->mj = j; } return ret; } int Demo_GetI(Demo* pThis) { struct ClassDemo* obj = (struct ClassDemo*)pThis; return obj->mi; } int Demo_GetJ(Demo* pThis) { struct ClassDemo* obj = (struct ClassDemo*)pThis; return obj->mj; } // 6. 定义虚函数表中指针所指向的具体函数 static int Demo_Virtual_Add(Demo* pThis, int value) { struct ClassDemo* obj = (struct ClassDemo*)pThis; return obj->mi + obj->mj + value; } // 5. 分析具体的虚函数!!!! int Demo_Add(Demo* pThis, int value) { struct ClassDemo* obj = (struct ClassDemo*)pThis; return obj->vptr->pAdd(pThis, value); } void Demo_Free(Demo* pThis) { free(pThis); } Derived* Derived_Create(int i, int j, int k) { struct ClassDerived* ret = (struct ClassDerived*)malloc(sizeof(struct ClassDerived)); if( ret != NULL ) { ret->d.vptr = &g_Derived_vtbl; ret->d.mi = i; ret->d.mj = j; ret->mk = k; } return ret; } int Derived_GetK(Derived* pThis) { struct ClassDerived* obj = (struct ClassDerived*)pThis; return obj->mk; } static int Derived_Virtual_Add(Demo* pThis, int value) { struct ClassDerived* obj = (struct ClassDerived*)pThis; return obj->mk + value; } int Derived_Add(Derived* pThis, int value) { struct ClassDerived* obj = (struct ClassDerived*)pThis; return obj->d.vptr->pAdd(pThis, value); } Main.c #include "stdio.h" #include "test.h" void run(Demo* p, int v) {     int r = Demo_Add(p, v);          printf("r = %d\n", r); } int main() {     Demo* pb = Demo_Create(1, 2);     Derived* pd = Derived_Create(1, 22, 333);          printf("pb->add(3) = %d\n", Demo_Add(pb, 3));     printf("pd->add(3) = %d\n", Derived_Add(pd, 3));          run(pb, 3);     run(pd, 3);          Demo_Free(pb);     Demo_Free(pd);          return 0; }
点赞 评论

相关推荐

头像
10-15 22:27
已编辑
门头沟学院 C++
罗格镇的小镇做题家:我投了hr打电话来说学历太低了不符合要求,建议投荣耀,结果荣耀也投了一定水花没有,非本211硕
投递华为等公司10个岗位
点赞 评论 收藏
分享
牛客网
牛客企业服务