C++ 中通过函数名字的字符串调用函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weiwei_c/article/details/49745953
#include<iostream>
#include <string>
#include <map>

using namespace std;

int add(int i,int j){ return i+j; }
int sub(int i,int j){ return i-j; }

typedef int (*FnPtr)(int,int);

int main()
{
     map<string,FnPtr> myMap;

     myMap["add"] = add;
     myMap["sub"] = sub;

     std::string s("add");
     int res=myMap[s](1,2);
    
     cout<<res<<endl;
     return 0;
}

上述的代码中就是通过“add”、“sub”字符串调用add和sub函数。

猜你喜欢

转载自blog.csdn.net/weiwei_c/article/details/49745953