#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct vtable {
void (*fun)();
};
struct father {
struct vtable *vptr;
char str[128];
};
struct son {
struct vtable *vptr;
char str[128];
};
void father_print()
{
printf("I am father func/n");
}
void son_print()
{
printf("I am son func/n");
}
void test(struct father *f)
{
f->vptr->fun();
}
int main()
{
struct vtable f_fun, s_fun;
f_fun.fun = father_print;
s_fun.fun = son_print;
struct father f;
struct son s;
f.vptr = &f_fun;
s.vptr = &s_fun;
strcpy(f.str, "father");
strcpy(s.str, "son");
test(&f);
test((struct father *)&s);
return 0;
}
用c语言模拟虚函数
最新推荐文章于 2024-07-13 14:34:09 发布
本文介绍了如何使用C语言来模拟实现虚函数的功能。通过定义结构体`vtable`存储函数指针,创建`father`和`son`结构体,并分别设置各自的虚表指针,调用`test`函数来执行不同对象的打印方法。最终,`father`和`son`对象将根据其关联的虚函数指针执行相应的`father_print`或`son_print`函数。

最低0.47元/天 解锁文章
387

被折叠的 条评论
为什么被折叠?



