///
#include <iostream>
using namespace std;
//自写C模拟C++多态
//类A中虚函数
void f1(){
cout<<"A f1\n";
}
void f2(int i){
cout<<"A f2\n";
}
//虚函数表,存虚函数的地址
typedef struct avtbl{
void (*pf1)(void);
void (*pf2)(int);
}avtbl;
//类A中的虚表
avtbl g_avtbl={&f1,&f2};
//类A中的最开始为虚表指针,其其它是类中的非静态数据成员
typedef struct A{
avtbl *pavtbl;
int num1;
}A;
//类A的构造函数,有个隐含形参this
void InitA(A *a){
a->pavtbl=&g_avtbl;
a->num1=0X123;
}
//子类B的与类A中的类型相同的虚函数,覆盖了类A的虚函数
void sf1(){
cout<<"B sf1\n";
}
//子类B自己的虚函数
void f3(char* s){
cout<<"B f3 "<<s<<endl;
}
//子类B的虚函数表
typedef struct bvtbl{
avtbl a_avtbl;
void (*f3)(char *);
}bvtbl;
//子类B的虚表
bvtbl g_bvtbl={{&sf1,&f2},&f3};
//子类B中包含基类A的内容,其它是自己的成员
typedef struct B{
A a;
int num2;
}B;
//对子类B初始化
void InitB(B*b){
InitA((A*)b);
(b->a).pavtbl=(avtbl*)&g_bvtbl;
b->num2=0X1234;
}
//测试
void Test(A *p){
//调用子类的f1函数
(*((p->pavtbl)->pf1))();
}
void main(){
B b;
A *p;
InitB(&b);
p=(A*)&b;
(*((bvtbl*)(p->pavtbl))->f3)("hello");
Test((A*)&b);
system("pause");
}