字符串和成员函数指针的C++ Map

标签 c++ map pointer-to-member

嘿,所以我正在制作一个以字符串为键、成员函数指针为值的映射。我似乎无法弄清楚如何添加到 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::insertstd::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++ FAQ - Pointers to member functions

关于字符串和成员函数指针的C++ Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419202/

相关文章:

c++ - 分配给 double 的数字上的 F 后缀

c++ - 有什么办法可以使 SHFileOperation 成为模态吗?

C++ 方法指针调用产生 undefined symbol 错误?

C++ 指向成员成员的指针?

r - 使用 R 中的美国各州数据绘制(填充颜色) map

c++ - 如何将函数指针(我们不知道参数的函数)声明为类成员?

c++ - 如何在字符串和分类器对象 ptr 之间创建映射

c++ - 如何在模板实例化中强制将 char[] 转换为 char*?

java - Map.containsKey() 有用吗?

ruby - 从 map 返回多个值