Chinaunix首页 | 论坛 | 博客
  • 博客访问: 305154
  • 博文数量: 85
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 800
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-18 15:21
文章分类

全部博文(85)

文章存档

2017年(1)

2016年(19)

2015年(55)

2014年(10)

我的朋友

分类: C/C++

2014-12-27 15:26:06

1.函数指针
    1.1定义函数指针

    一般的函数指针可以这么定义:
  int(*func)(int,int);
  表示一个指向含有两个int参数并且返回值是int形式的任何一个函数指针. 假如存在这样的一个函数:
        int add2(int x,int y)
  {
  return x+y;
  }
  那么在实际使用指针func时可以这样实现:
  func=&add2; //指针赋值,或者func=add2; add2与&add2意义相同
  printf("func(3,4)=%d\n",func(3,4));
  事实上,为了代码的移植考虑,一般使用typedef定义函数指针类型.
  typedef int(*FUN)(int,int);
  FUN func=&add2;
  func();
       //理解函数指针了再理解下面的吧!
        
    1.2 结构体内定义函数指针
    其实在结构体中,也可以像一般变量一样,包含函数指针变量(注意:不是函数,只是指针变量)。C语言中的struct是最接近类的概念,但是在C语言的struct中只有成员,不能有函数,但是可以有指向函数的指针,这也就方便了我们使用函数了。举个例子,如下:
  1. #include   
  2. #include   
  3. #include   
  4.   
  5. typedef struct student  
  6. {  
  7.     int id;  
  8.     char name[50];   
  9.     void (*initial)();  
  10.     void (*process)(int id, char *name);  
  11.     void (*destroy)();  
  12. }stu;  
  13.   
  14. void initial()  
  15. {  
  16.     printf("initialization...\n");  
  17. }  
  18.   
  19. void process(int id, char *name)  
  20. {  
  21.     printf("process...\n%d\t%s\n",id, name);  
  22. }  
  23.   
  24. void destroy()  
  25. {  
  26.     printf("destroy...\n");  
  27. }  
  28.   
  29. int main()  
  30. {  
  31.     stu *stu1;  
  32.     //在VC和TC下都需要malloc也可以正常运行,但是linux gcc下就会出错,为段错误,必须malloc  
  33.     stu1=(stu *)malloc(sizeof(stu));  
  34.     //使用的时候必须要先初始化  
  35.     stu1->id=1000;  
  36.     strcpy(stu1->name,"C++");  
  37.     stu1->initial=initial;  
  38.     stu1->process=process;  
  39.     stu1->destroy=destroy;  
  40.     printf("%d\t%s\n",stu1->id,stu1->name);  
  41.     stu1->initial();  
  42.     stu1->process(stu1->id, stu1->name);  
  43.     stu1->destroy();  
  44.     free(stu1);  
  45.     return 0;  
  46. }  
更好的例子看看 

typedef函数指针用法


阅读(757) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~