#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语言模拟虚函数
![](https://img-home.csdnimg.cn/images/20240711042549.png)