接上条评论,代码实现如下,欢迎讨论
typedef struct _Base Base;
typedef void (*fptrDisplay)(Base*);
typedef void (*fptrDelete)(Base*);
void DisplayBase(Base* );
void DeleteBase(Base*);
typedef struct _Base
{
void* pDeriveObj;
int a;
int b;
fptrDisplay Display;
fptrDelete Delete;
}Base;
Base* new_base(int a, int b)
{
Base* pObj = NULL;
pObj = (Base*)malloc(sizeof(Base));
if (pObj == NULL)
{
return NULL;
}
// 当创建基类对象时指向自己
pObj->pDeriveObj = pObj;
pObj->a = a;
pObj->b = b;
pObj->Display = DisplayBase;
pObj->Delete = DeleteBase;
return pObj;
}
void DisplayBase(Base* base)
{
printf("member: a:%d\t b:%d\n", base->a, base->b);
}
void DeleteBase(Base* base)
{
printf("base destructor!\n");
free(base);
}
typedef struct _Derive
{
Base* pBaseObj;
int c;
int d;
}Derive;
void DeriveDisplay(Base* base);
void DeriveDelete(Base* base);
Base* new_Derive(int a, int b, int c, int d)
{
Derive* pObj = NULL;
Base* pBaseObj = new_base(a, b);
pObj = malloc(sizeof(Derive));
if (!pObj)
{
pBaseObj->Delete(pBaseObj);
return NULL;
}
pBaseObj->pDeriveObj = pObj;
pObj->pBaseObj = pBaseObj;
pObj->c = c;
pObj->d = d;
pBaseObj->Display = DeriveDisplay;
pBaseObj->Delete = DeriveDelete;
return pBaseObj;
}
void DeriveDisplay(Base* base)
{
Derive* pDeriveObj = (Derive*)(base->pDeriveObj);
printf("member:base:a:%d\t base:b:%d\nderive:c:%d\t derive:d:%d\n", base->a, base->b, pDeriveObj->c, pDeriveObj->d);
}
void DeriveDelete(Base* base)
{
printf("derive destructor!\n");
free(base->pDeriveObj);
free(base);
}
int main()
{
Base* pBase = new_base(1, 2);
Base* pDerive = new_Derive(3, 4, 5, 6);
pBase->Display(pBase);
pDerive->Display(pDerive);
pBase->Delete(pBase);
pDerive->Delete(pDerive);
}
展开