函数指针

函数指针数组(转移表)

形式如下:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值