函数指针
来源:互联网 发布:mysql unique 编辑:程序博客网 时间:2024/06/13 21:50
函数指针指向的是函数而非对象。如我们有这样一个函数:
int add(int const a,const int b){ return a+b;}
要声明一个指向该函数的指针,只需要用指针名替换函数名即可:
int (*point_func)(int const a,const int b){ return a+b;}
*point_func 两端的括号必不可少。如果缺少括号,则 point_func 是一个返回值为int 指针的函数:
int *point_func(int const a,const int b){ return a+b;}
使用函数指针
当我们声明一个函数指针后,将所需指向的函数的地址赋给函数指针:
point_func=&add;
&符号也可以不加,这也是可以的,就如同数组名arr一样,不加&符号自动转换成指针:
point_func=add;
当完成初始化后我们就可以使用函数指针了:
int result=point_func(3,4);
同样有另一种写法:
int result=(*point_func)(3,4);
重载函数的指针
当使用重载函数后,必须清晰的定义到底应该使用哪个函数。
int f(int *);int f(unsigned int );int (*pf)(unsigned int)=f;//指向f(unsigned int)
函数指针形参
我们不能在函数的形参里面定义函数类型的,但我们可以使用指向函数类型的形参。此时,看起来形参是函数类型,实际上是当成指针使用。
int fun(const int a,const int b,int pf(const int ,const int));
int fun(const int a,const int b,int (*pf)(const int ,const int));
上面是显式定义了一个函数指针。
fun(a,b,add);
函数指针的应用
比如我们有两个函数,只有当运行时才知道进行的是加、减、乘、除操作之一,此时就应该使用函数指针:
#include <iostream>using namespace std;int add(int const a,const int b){ return a+b;}int sub(const int a,int const b){ return a-b;}int multiply(const int a,const int b){ return a*b;}int divide(const int a,const int b){ return a/b;}int fun(int a,int b,int (pf)(const int ,const int)){ return pf(a,b);}int main(int argc, const char * argv[]){ // insert code here... int (*pf)(const int ,const int); int i; cin>>i; if(i%4==0) { pf=add; } else if(i%4==1) { pf=sub; } else if(i%4==2) { pf=multiply; } else { pf=divide; } cout<<fun(3,4,pf)<<endl; return 0;}
当我们需要函数作为参数和动态调用函数的时候,我们可以使用指向函数的指针。
0 0
- 指针函数 函数指针
- 函数指针/指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 指针函数,函数指针
- 函数指针,指针函数,
- 指针函数,函数指针
- 函数指针 指针函数
- 函数指针、指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 函数指针&指针函数
- 指针函数 函数指针
- 指针函数 &函数指针
- 函数指针&指针函数
- void指针 函数指针
- 学习计划[201405 ~ 201410]
- 在CentOS 6.3中安装与配置JDK-7
- w3shool中的TCP/IP (I)
- ubuntu10.04 Qt5.2.1链接mysql出现QMYSQL driver not loaded的问题!!!!
- struts2 get 和set 方法
- 函数指针
- cocos2dx游戏开发学习笔记2-从helloworld开始
- NYOJ 7 街区最短路径问题
- Java(TM) Platform SE binary 已停止工作
- Web Service概述 及 应用案例
- 纯CSS3文字效果推荐
- poj 1852 ants
- 利用cx_Freeze将py文件打包成exe文件(图文全解)
- ios--时间格式化--NSDateFormatter