函数指针
来源:互联网 发布:sql server 2008服务器 编辑:程序博客网 时间:2024/06/13 18:36
函数指针数组(转移表)
形式如下:
int (*f[4])(); //有4个参数的函数指针 数组
应用转移表:如下为一个利用这个,实现加、减、陈、除。
#include <iostream>using namespace std;//转移表: 函数指针 数组int add(int a,int b){ return a+b;}int sub(int a,int b){ return a-b;}int div(int a,int b){ return a/b;}int mul(int a,int b){ return a*b;}//函数指针数组 赋值//首先data是一个数组有4个元素,其次每个元素都是一个函数指针int (*data[4])(int,int) = {add,&sub,mul,div};void print_cal_interface(){ cout << "**************" << endl; cout << "** 1.add **" << endl; cout << "** 2.sub **" << endl; cout << "** 3.mul **" << endl; cout << "** 4.div **" << endl; cout << "** 0.exit **" << endl; cout << "**************" << endl; cout << "input your choice: ";}int main(){ int choice; int x,y; int ret; while(1){ print_cal_interface(); cin >> choice; if(choice == 0) break; else if(choice < 0 || choice > 4){ cout << "your choice is ill!" << endl; continue; } cout << "input two num: "; cin >> x >> y; ret = data[choice-1](x,y); cout << "ret: " << ret << endl; } return 0;}
函数指针(回调,让它作参数)
形式如下:
给函数指针起别名:
typedef int (*FP)(int, int);//有两个参数的函数指针int (*f)();//无参的函数指针f
应用: 利用一个函数查找,一维数组中的最大值和最小值
#include <iostream>using namespace std;int comp1(int a,int b){ return a - b;}int comp2(int a,int b){ return b - a;}//可以利用所传函数的入口地址不同,来调用不同的函数实现不同的功能int get_Min_Max(int *data,int len,int (*comp)(int,int)){ int num = data[0]; int i = 1; for(;i < len;i++){ //comp1求最小 if(comp(num,data[i]) > 0) num = data[i]; } return num;}int main(){ int data[] = {2,5,1,0,89,12}; int len = sizeof(data)/sizeof(int); cout << "min: " << get_Min_Max(data,len,comp1) << endl; cout << "max: " << get_Min_Max(data,len,comp2) << endl; return 0;}
0 0
- 指针函数 函数指针
- 函数指针/指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 指针函数,函数指针
- 函数指针,指针函数,
- 指针函数,函数指针
- 函数指针 指针函数
- 函数指针、指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 函数指针&指针函数
- 指针函数 函数指针
- 指针函数 &函数指针
- 函数指针&指针函数
- void指针 函数指针
- Could not publish server configuration for Tomcat v6.0 Server at localhost
- StringBufferDemo
- Android Imagview快速设置、切换图像时,闪烁的问题解决
- 严重: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error cre
- 小程序
- 函数指针
- NOIP 2009 T3 自由贸易题解
- Mms彩信添加联系人和日历时,时间格式与系统时间格式不相符的问题
- 友善之臂の用自己的qt4.7程序替换掉友善之臂的start qt4.7.0
- StringMethodDemo.java
- Android 自动适应字体大小的EditText
- unique函数
- 排序算法的代码整理
- Fragment实例,数据存储,数据库SQLite