Nit*_*ess 6 c struct function-pointers
我想在结构中使用函数指针与在结构中封装函数有关...?如果是这样,那究竟是如何实现的?
它在结构中有一个函数指针而不是简单地定义函数会带来什么好处呢?
结构内部的函数指针是C语言中对象编程的基础(请参见http://www.planetpdf.com/codecuts/pdfs/ooc.pdf)。对于中大型C项目确实如此。
一个例子:
标头:
typedef struct TPile
{
int(*Push)(struct TPile*, int);
int(*Pop)(struct TPile*);
void(*Clear)(struct TPile*);
void(*Free)(struct TPile*);
int(*Length)(struct TPile*);
void(*View)(struct TPile*);
int Nombre;
struct Titem *Top;
} TPile ;
Run Code Online (Sandbox Code Playgroud)
资源:
TPile TPile_Create()
{
TPile This;
TPile_Init(&This);
This.Free = TPile_Free;
return This;
}
TPile* New_TPile()
{
TPile *This = malloc(sizeof(TPile));
if(!This) return NULL;
TPile_Init(This);
This->Free = TPile_New_Free;
return This;
}
void TPile_Clear(TPile *This)
{
Titem *tmp;
while(This->Top)
{
tmp = This->Top->prec;
free(This->Top);
This->Top = tmp;
}
This->Nombre = 0;
}
Run Code Online (Sandbox Code Playgroud)