函数指针_2

一、举一个简单的例子理解函数指针

#include <iostream>
#include <cstdlib>
using namespace std;

typedef int(*MATH_OPERATION)(int,int);
int run(int,int,MATH_OPERATION);
int _add(int,int);
int _sub(int,int);
int _mul(int,int);
int _div(int,int);

#define DEBUG
int main()
{
    int a,b,result;
    unsigned int e;
    cout<<"Please enter two numbers:\n";
    cin>>a;
    cin>>b;
    MATH_OPERATION p;
    //通过设置p指向不同的入口函数实现不同的函数操作
    p=_add;
    // p=_sub;
    // p=_mul;
    // p=_div;
    result = run(a,b,p);
    cout<<result<<endl;
    return 0;
}
//run这个函数就是实现四则运算,"+" "-" "×" "/",传入一个函数指针和一个附加参数来决定
//因为我实现的是四则运算,但是具体实现哪一个运算由用户决定,所以利用函数指针可以实现未来的函数
//函数指针指向的函数叫回调函数,依赖后续设计才能确定的被调函数
int run(int a,int b,MATH_OPERATION p)
{
    if(!p)
    {
        cout<<"ERROR! MATH_OPERATION p:Parameter Illeagal!"<<endl;
        exit(1);
    }
    return (*p)(a,b);
}
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 a/b;}

首先定义啦函数指针类型MATH_OPERATION,实现四则运算,可以通过修改函数指针p来实现指向不同的函数入口地址 ,但是每次修改函数入口地址都要修改函数指针的指向

二、下面的例子是上面代码的改进,在run函数增加了一个附加参数,通过判断附加参数的值来实现p指向不同的参数

#include <iostream>
#include <cstdlib>
using namespace std;

#include "test_1.h"
#define DEBUG
int main()
{
    int a,b,result;
    unsigned int e;
    cout<<"Please enter two numbers:\n";
    cin>>a;
    cin>>b;
    cout<<"Please enter number of math operation E(1~4)\n";
    cin>>e;
    MATH_OPERATION p;
    result = run(a,b,p,e);
    #ifdef DEBUG
    if(e==1) cout<<"The sum of "<<a<<"+"<<b<<" is "<<result<<endl;
    if(e==2) cout<<"The sub of "<<a<<"-"<<b<<" is "<<result<<endl;
    if(e==3) cout<<"The mul of "<<a<<"×"<<b<<" is "<<result<<endl;
    if(e==4) cout<<"The div of "<<a<<"/"<<b<<" is "<<result<<endl;
    #endif
    return 0;
}
//run这个函数就是实现四则运算,"+" "-" "×" "/",传入一个函数指针和一个附加参数来决定
//因为我实现的是四则运算,但是具体实现哪一个运算由用户决定,所以利用函数指针可以实现未来的函数
//函数指针指向的函数叫回调函数,依赖后续设计才能确定的被调函数
int run(int a,int b,MATH_OPERATION p,unsigned int e)
{
    if(!p)
    {
        cout<<"ERROR! MATH_OPERATION p:Parameter Illeagal!"<<endl;
        exit(1);
    }
    if(e==1){p=_add;return(*p)(a,b);}
    else if(e==2) {p=_sub;return(*p)(a,b);}
    else if(e==3) {p=_mul;return(*p)(a,b);}
    else if(e==4) {p=_div;return(*p)(a,b);}
    else {cout<<"ERROE! Parameter e is between 1 and 4"<<endl;exit(1);}
}
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 a/b;}

test.h

typedef int(*MATH_OPERATION)(int,int);

int run(int,int,MATH_OPERATION,unsigned int);

int _add(int,int);

int _sub(int,int);

int _mul(int,int);

int _div(int,int);

这样,run函数可以提前写好,然后p的指向函数还可以通过附加参数的值进行修改,在run中实现各种不同函数的功能。

猜你喜欢

转载自blog.csdn.net/Li_haiyu/article/details/81738878