Thi*_*ngs 4 c++ member-function-pointers 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)
{
}
Run Code Online (Sandbox Code Playgroud)
Ola*_*che 10
见std::map::insert和std::map对value_type
myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));
Run Code Online (Sandbox Code Playgroud)
并为 operator[]
myMap["test"] = &Test::TestFunc;
Run Code Online (Sandbox Code Playgroud)
如果没有对象,则不能使用指向成员函数的指针.您可以使用指向成员函数的指针与类型的对象Test
Test t;
myFunc f = myMap["test"];
std::string s = (t.*f)("Hello, world!");
Run Code Online (Sandbox Code Playgroud)
或指向类型的指针 Test
Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");
Run Code Online (Sandbox Code Playgroud)