我试图在下面的代码,但该程序崩溃的工作:将回调函数传递给std :: map的最佳方式是什么?
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef void (*callBackMethod)(string);
class CTest
{
private:
map<string, callBackMethod> mapMethod;
void testMethod(string msg)
{
cout << msg << endl;
}
public:
CTest()
{
addFunction("AA", (callBackMethod) &CTest::testMethod);
}
void addFunction(string funName, callBackMethod methodName)
{
mapMethod[funName] = methodName;
}
callBackMethod getMethod(string funName)
{
auto fun = mapMethod.find(funName);
if(fun == mapMethod.end()) { return nullptr; }
return fun->second;
}
void runFunction(string funName)
{
getMethod(funName)("test");
}
};
int main()
{
CTest test;
test.runFunction("AA");
return 0;
}
我有,我需要私有方法传递到地图的要求。该程序编译时出现警告:
converting from 'void (CTest::*)(std::__cxx11::string) {aka void (CTest::*)(std::__cxx11::basic_string<char>)}' to 'callBackMethod {aka void (*)(std::__cxx11::basic_string<char>)}'
当我执行此操作时,它崩溃。
当我将回调方法移出它的工作类之外。我的要求是让程序流动(隐藏需要添加到地图的外部呼叫的方法)。
期待您的意见。
为什么地球上你会认为将一个指向成员函数的指针指向函数是个好主意? –
@ T.C。那你有什么建议?如果你愿意,请修改代码。 – programmer
[如何将非静态成员函数作为回调函数传递?](http://stackoverflow.com/questions/2097738/how-to-pass-a-non-static-member-function-as- a-callback) –