Chinaunix首页 | 论坛 | 博客
  • 博客访问: 639775
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: C/C++

2011-04-08 13:49:44

typedef定义函数指针的用法
http://lengjing.iteye.com/blog/910392
1. typedef有点类似于#define宏,用来定义一个同义的新的类型。用typedef来定义函数指针形式如下:
C++代码  收藏代码
  1. typdef int (*pFunc)(intint);  
typdef int (*pFunc)(int, int);
如果我们有一个函数:
C++代码  收藏代码
  1. int Add(int a, int b)  
  2. {  
  3.     return a +b;  
  4. }  
int Add(int a, int b) { return a +b; }
那么我们可以这样用:
C++代码  收藏代码
  1. pFunc pf;  
  2. pf = Add;  
  3. int n = pf(3, 4);   
pFunc pf; pf = Add; int n = pf(3, 4);
如意对于上面的定义可以这样理解:去掉typedef就形如正常的定义。同样的方式我们可以定义指针类型:
C++代码  收藏代码
  1. typedef int *p;   
typedef int *p;
这样就可以用p来定义一个int型的指针类型了。

2. 一个复杂点的例子:
C++代码  收藏代码
  1. typedef int (*pFunc)(intint);  
  2. pFunc function1(char op);  
  3.   
  4. // 上面的定义等同下面的定义:  
  5. // int (*function1(char op))(int, int);  
  6.   
  7. // 以下代码演示函数指针的用法  
  8. int add(int a, int b)  
  9. {  
  10.     return a + b;  
  11. }  
  12.   
  13. int (*function2(char op))(intint)  
  14. {  
  15.     return function1(op);  
  16. }  
  17.   
  18. pFunc function1(char op)  
  19. {  
  20.     switch (op) {  
  21.         case '+'return add;  
  22.         defaultreturn NULL;      
  23.     }  
  24.   
  25.     return NULL;  
  26. }  
  27.   
  28. int calc_func(int a, int b, char op)  
  29. {  
  30.     pFunc fp = function1(op);  
  31.     return fp(a, b);  
  32. }  
  33.   
  34. // 计算a、b的和  
  35. int a = 100, b = 200;  
  36. int c = calc_func(a, b, '+'); 
阅读(2578) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~