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源码学习结果,如有错误,请多多指教。