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

#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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。