首页 > 其他 > 详细

函数指针与typedef

时间:2018-08-08 16:28:52      阅读:156      评论:0      收藏:0      [点我收藏+]
#include<bits/stdc++.h>
using namespace std;

//定义一个函数指针
typedef int (*Fun)(int,int);

int add(int a,int b){return a+b;}
int sub(int a,int b){return a-b;}
int mul(int a,int b){return a*b;}
int _div(int a,int b){return b?a/b:-1;}

Fun fun(char op)
{
    switch(op)
    {
    case +:return add;
    case -:return sub;
    case *:return mul;
    case /:return _div;
    default:return NULL;
    }
    return NULL;
}

//方法1
//返回值为一个拥有两个int参数、返回类型为int的函数指针 
int (*for_fun(char op))(int, int)
{
    return fun(op);
}
//方法2
//直接调用函数
int fun_cal(int a,int b, char op)
{
    Fun fp=fun(op);//定义一个函数指针,接收两个int整数
    if(fp)
        return fp(a,b);
    else
        return -1;
}

int main()
{
    cout<<"100+20="<<fun_cal(100,20,+)<<endl;
    cout<<"100-20="<<(*for_fun(-))(100,20)<<endl;
    cout<<"100*20="<<fun_cal(100,20,*)<<endl;
    cout<<"100/20="<<(*for_fun(/))(100,20)<<endl;
    return 0;
}

函数指针与typedef

原文:https://www.cnblogs.com/ybf-yyj/p/9443615.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!