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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值