C语言实现简单多态(参考libevent 多路复用的使用)

C++多态:运行时会根据对象的实际类型来调用相应的函数

C语言实现多态,主要是通过函数指针。

简单实现代码:

定义一个结构体,结构体内容为各种接口的函数指针,相当于定义C++抽象类和纯虚函数

struct eventop {
    const char *name;
    void *(*init)(void);
    int (*add)(void);
    int (*del)(void);
    int (*dispatch)(void);
    void (*dealloc)(void);
    /* set if we need to reinitialize the event base */
    int need_reinit;
};

定义一个struct eventop变量,相当于C++派生一个类

static void *poll_init(void)
{
    printf("poll_init\n") ;
    return NULL ;
}
static int poll_add(void)
{
    printf("poll_add\n") ;
    return 0 ;
}
static int poll_del(void)
{
    printf("poll_del\n");
    return 0 ;
}
static int poll_dispatch(void)
{
    printf("poll_dispatch\n");
    return 0 ;
}
static void poll_dealloc(void)
{
    printf("poll_dealloc\n");

}
const struct eventop pollops = {
    "poll",
    poll_init,
    poll_add,
    poll_del,
    poll_dispatch,
    poll_dealloc,
    0
};

再定义一个struct eventop变量,相当于C++再派生一个类

static void *select_init(void){
   printf("select_init\n");
   return NULL ;
}
 
static int select_add(void)
{
    printf("select_add\n");
    return 0 ;
}
static int select_del(void)
{
    printf("select_del\n");
    return 0 ;
}
static int select_dispatch	(void)
{
    printf("select_dispatch\n");
    return 0 ;
}
static void select_dealloc(void)
{
    printf("select_dealloc\n");
 
}
const struct eventop selectops = {
    "select",
    select_init,
    select_add,
    select_del,
    select_dispatch,
    select_dealloc,
    0
};


现在定义一个工厂接口:

static const struct eventop *eventops[] = {
 
    &pollops,
    &selectops,
 
    NULL
};
typedef enum demultiplex
{
    e_poll = 0 ,
    e_select ,
}E_TYPE ;
 
static void factory(E_TYPE type)
{
    const struct eventop *evsel;
    evsel = eventops[type] ;
    evsel->init() ;
    evsel->del();
    evsel->add() ;
    evsel->dealloc();
    evsel->dispatch();
}


这个就是简单实现的C语言多态。

测试代码:

int main(int argc, char *argv[])
{
    E_TYPE type = e_select; //type = e_poll ;
    factory(type);
}
 


输出结果:

select_init

select_del

select_add

select_dealloc

select_dispatch


此是本人阅读libevent源码学习结果,如有错误,请多多指教。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值