字符串和成员函数指针的映射

C++ Map of string and member function pointer

本文关键字:映射 指针 函数 成员 字符串      更新时间:2023-10-16

嘿,所以我正在制作一个映射字符串作为关键和成员函数指针作为值。我似乎不知道如何添加到地图上,这似乎不工作。

#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)
{
}

value_type参见std::map::insertstd::map

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 -指向成员函数的指针