#include <stdio.h>
#include <stdlib.h>
typedef void (*FUNC_TYPE)(void *);
//虚函数表结构
struct vtbl
{
FUNC_TYPE dance;
FUNC_TYPE jump;
};
//基类
struct base
{
/*virtual table*/
struct vtbl *vptr;
FUNC_TYPE dance;
FUNC_TYPE jump;
};
void dance(void *vPtr)
{
struct base * b = (struct base *)vPtr;
b->vptr->dance(vPtr);
}
void jump(void *vPtr)
{
struct base * b = (struct base *)vPtr;
b->vptr->jump(vPtr);
}
void base_dance(void *this)
{
printf("base dance\n");
}
void base_jump(void *this)
{
printf("base jump\n");
}
/* global vtable for base */
struct vtbl base_table =
{
base_dance,
base_jump
};
void ConstructBase(void * vPtr)
{
struct base * this = (struct base *)vPtr;
this->vptr = &base_table;
this->dance = dance;
this->jump = jump;
return ;
}
//基类的构造函数
struct base * new_base()
{
struct base *temp = (struct base *)malloc(sizeof(struct base));
temp->vptr = &base_table;
temp->dance = dance;
return temp;
}
//派生类
struct Derived
{
struct base m_base;
/*derived members */
int high;
};
void derived_dance(void * this)
{
/*implementation of derived's dance function */
printf("derived dance\n");
}
void derived_jump(void * this)
{
/*implementation of Derived's jump function */
struct Derived* temp = (struct Derived *)this;
printf("Derived jump:%d\n", temp->high);
}
/*global vtable for Derived */
struct vtbl Derived_table =
{
&derived_dance,
&derived_jump
};
void ConstructDerived(void * vPtr)
{
struct Derived * this = (struct Derived *)vPtr;
this->m_base.vptr = &Derived_table;
this->m_base.dance = dance;
this->m_base.jump = jump;
return ;
}
//派生类的构造函数
struct Derived * new_derived(int h)
{
struct Derived * this= (struct Derived *)malloc(sizeof(struct Derived));
this->m_base.vptr = &Derived_table;
this->m_base.dance = dance;
this->m_base.jump = jump;
this->high = h;
return this;
}
int main(void)
{
struct base * bas = new_base();
//这里调用的是基类的成员函数
bas->vptr->dance((void *)bas);
bas->vptr->jump((void *)bas);
struct Derived * child = new_derived(100);
//基类指针指向派生类
bas = (struct base *)child;
//这里调用的其实是派生类的成员函数
bas->vptr->dance((void *)bas);
bas->vptr->jump((void *)bas);
bas->dance((void *)bas);
bas->jump((void *)bas);
//-----------------------------------------------
struct base Base2;
ConstructBase(&Base2);
Base2.dance(&Base2);
Base2.jump(&Base2);
return 0;
}
运行结果:
base dance
base jump
derived dance
Derived jump:100
derived dance
Derived jump:100
base dance
base jump