C++ Map of string and member function pointer

此生再无相见时 提交于 2019-12-07 07:25:20

问题


Hey so I am making a map with string as the key and a member function pointer as the value. I can't seem to figure out how to add to the map, this doesn't seem to be working.

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

回答1:


See std::map::insert and std::map for value_type

myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));

and for operator[]

myMap["test"] = &Test::TestFunc;

You cannot use a pointer to member function without an object. You can use the pointer to member function with an object of type Test

Test t;
myFunc f = myMap["test"];
std::string s = (t.*f)("Hello, world!");

or with a pointer to type Test

Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");

See also C++ FAQ - Pointers to member functions



来源:https://stackoverflow.com/questions/14419202/c-map-of-string-and-member-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!