#include "malloc.h"
#include <stdio.h>
struct Base {
struct VFunc* vF;
};
struct VFunc {
void (*print)(Base* b);
};
void print(Base* b) {
printf("%s\n", "我是Base!");
}
struct Derived {
struct VFunc* vF;
int a;
};
void print_Derived(Base* b) {
Derived* curr = (Derived*)b;
printf("%s%d\n", "我是Derived!a是", curr->a);
}
Base* ctor_Derived(int in) {
Derived* b = (Derived*)malloc(sizeof(struct Derived));
VFunc v{ &print_Derived };
b->vF = &v;
b->a = in;
return (Base*)b;
}
Base* ctor() {
Base* a = (Base*)malloc(sizeof(struct Base));
VFunc v{ &print};
a->vF = &v;
return a;
}
int main() {
Base* b = ctor_Derived(1);
if (!b) return -1;
b->vF->print(b);
Base* a = ctor();
a->vF->print(a);
return 0;
}
总结
- 虚表封装成一个
struct VFunc
,里面都是函数指针
-
struct Base
需要虚表指针,并且声明定义虚函数
-
struct Derived
需要虚表指针,相当于继承,并且声明定义虚函数
- 构造函数需要自己写,构造虚表,并使自己的虚表指针指向序表
- 每个对象逻辑链都有一个虚表,比如
Base->Derived1
和Base->Derived2
就有两个虚表
- 因为
强制转换
,Derived的顺序不能改
struct Base {
struct VFunc* vF;
};
struct Derived {
struct VFunc* vF;
int a;
};
c语言实现多态