嘿,所以我正在制作一个以字符串为键、成员函数指针为值的映射。我似乎无法弄清楚如何添加到 map ,这似乎不起作用。
#include <iostream>
#include <map>
using namespace std;
typedef string(Test::*myFunc)(string);
typedef map<string, myFunc> MyMap;
class Test
{
private:
MyMap myMap;
public:
Test(void);
string TestFunc(string input);
};
#include "Test.h"
Test::Test(void)
{
myMap.insert("test", &TestFunc);
myMap["test"] = &TestFunc;
}
string Test::TestFunc(string input)
{
}
最佳答案
参见 std::map::insert
和 std::map
对于 value_type
myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));
对于 operator[]
myMap["test"] = &Test::TestFunc;
您不能在没有对象的情况下使用指向成员函数的指针。您可以将指向成员函数的指针与 Test
Test t;
myFunc f = myMap["test"];
std::string s = (t.*f)("Hello, world!");
或使用指向类型Test
Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");
关于字符串和成员函数指针的C++ Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419202/