美文网首页
C++ 返回函数指针的函数

C++ 返回函数指针的函数

作者: 鱼小莘 | 来源:发表于2020-05-02 14:52 被阅读0次
#include <iostream>

using namespace std;


int add(int a,int b){return a+b;}
int mul(int a,int b){return a*b;}

//返回函数指针的函数,第一种
typedef int OP(int,int);
OP* get_op(char c){
    if (c=='+')
        return add;
    else if (c=='*')
        return mul;
    else
        return nullptr;
}

//返回函数指针的函数,第二种
int (*op(char c))(int, int){
    if (c=='+')
        return add;
    else if (c=='*')
        return mul;
    else
        return nullptr;
}

//返回函数指针的函数,第三种,C++11
auto op2(char c) -> int (*)(int, int){
    if (c=='+')
        return add;
    else if (c=='*')
        return mul;
    else
        return nullptr;
}

//返回函数指针的函数,该指针指向 返回函数指针的函数,第一种
int (*(*pf_op())(char c))(int, int){
    return op2;
}
//返回函数指针的函数,该指针指向 返回函数指针的函数,第二种,C++11
auto pf_op2() -> auto (*)(char) -> int (*)(int, int){
     return op;
}

int main()
{
    int (*opt)(int,int) = op2('+');//get_op('*');//op('*');
    cout<<op('+')(1,2)<<endl;
    cout<<opt(1,2)<<endl;
    cout<<pf_op()('+')(1,2)<<endl;
    cout<<pf_op2()('+')(1,2)<<endl;
    return 0;
}

相关文章

网友评论

      本文标题:C++ 返回函数指针的函数

      本文链接:https://www.haomeiwen.com/subject/xsukghtx.html