C语言实现多态

#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;
}

总结

  1. 虚表封装成一个struct VFunc,里面都是函数指针
  2. struct Base需要虚表指针,并且声明定义虚函数
  3. struct Derived需要虚表指针,相当于继承,并且声明定义虚函数
  4. 构造函数需要自己写,构造虚表,并使自己的虚表指针指向序表
  5. 每个对象逻辑链都有一个虚表,比如Base->Derived1Base->Derived2就有两个虚表
  6. 因为强制转换,Derived的顺序不能改
struct Base {
	struct VFunc* vF;
};
struct Derived {
	struct VFunc* vF;
	int a;
};
posted @ 2021-08-21 23:11  肥斯大只仔  阅读(124)  评论(0编辑  收藏  举报