c中的struct内部的函数指针有什么用? [英] What good is a function pointer inside a struct in c?
本文介绍了c中的struct内部的函数指针有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我猜想在结构体内部使用函数指针与将函数封装在结构体中有关系...?如果是这样,那么这将如何实现?
I guess using a function pointer inside a struct has something to do with encapsulating a function within a structure...? If so, then how exactly is this achieved??
在结构中包含函数指针而不是简单地定义函数会带来什么好处?
And what good does it bring to have a function pointer inside a struct rather than simply defining the function?
推荐答案
function pointers inside structures are the base of object-programming in C (see http://www.planetpdf.com/codecuts/pdfs/ooc.pdf ). It is really really for medium-to-large C projects.
一个例子:
标题:
Header:
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 ;
来源:
Source:
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;
}
这篇关于c中的struct内部的函数指针有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文