结构体中的函数指针
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类型*/
};
每次都需要初始化,比较麻烦
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类型*/
};
每次都需要初始化,比较麻烦
相关文章推荐
- "解密"微信开放高级接口 企业如何应对
- android 使用POST提交数据
- Ubuntu 下配置 tftp 服务器
- 屏幕分辨率
- Javascript模块化编程:模块的写法
- window mysql5.6 忘记root密码 修改
- 利用最小二乘法拟合任意次函数曲线(C#)
- Sicily 1029. Rabbit 解题报告
- 【Android Developers Training】 14. 序言:管理Activity生命周期
- Xcode开启gcc/g++
- mysql sql语句大全
- 搞清楚LzoCodec和LzopCodec
- c#修改默认浏览器
- Cocos2d-x 中 Android.mk 自动添加源文件和头文件目录的路径
- (转)实战Memcached缓存系统(8)Memcached异步实时读写问题的解决方案SAC
- MyEclipse 10 下在线安装插件
- ALSA声卡驱动中的DAPM详解之七:dapm事件机制(dapm event)
- c# 操作Excel单元格属性
- R笔记
- 数据结构 字典树模板