用c语言模拟虚函数

本文介绍了如何使用C语言来模拟实现虚函数的功能。通过定义结构体`vtable`存储函数指针,创建`father`和`son`结构体,并分别设置各自的虚表指针,调用`test`函数来执行不同对象的打印方法。最终,`father`和`son`对象将根据其关联的虚函数指针执行相应的`father_print`或`son_print`函数。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值