您的位置:首页 > 其它

结构体中的函数指针

2013-11-28 15:32 302 查看
结构体中指向函数的指针                                          

C语言中的struct是最接近类的概念,但是在C语言的struct中只有成员,不能有函数,但是可以有指向函数的指针,这也就方便了我们使用函数了。举个例子,如下:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedefstruct student

{

 int id;

 char name[50]; 

 void (*initial)();

 void (*process)(int id, char *name);

 void (*destroy)();

}stu;

void initial()

{

 printf("initialization.../n");

}

void process(int id, char *name)

{

 printf("process.../n%d/t%s/n",id, name);

}

void destroy()

{

 printf("destroy.../n");

}

int main()

{

 stu *stu1;

//在VC和TC下都需要malloc也可以正常运行,但是linuxgcc下就会出错,为段错误,必须malloc

 stu1=(stu *)malloc(sizeof(stu));

 // 使用的时候必须要先初始化

 stu1->id=1000;

 strcpy(stu1->name,"xufeng");

 stu1->initial=initial;

 stu1->process=process;

 stu1->destroy=destroy;

 

 printf("%d/t%s/n",stu1->id,stu1->name);

 stu1->initial();

 stu1->process(stu1->id, stu1->name);

 stu1->destroy();

 free(stu1);

 return 0;

}

------------------------------------

c语言中,如何在结构体中实现函数的功能?把结构体做成和类相似,让他的内部有属性,也有方法

这样的结构体一般称为协议类,提供参考: 

struct { 

 intfuncid; 

 char *funcname; 

 int (*funcint)(); /* 函数指针int类型*/ 

 void (*funcvoid)(); /* 函数指针 void类型*/ 

}; 

每次都需要初始化,比较麻烦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: