C ++映射字符串和成员函数指针 [英] C++ Map of string and member function pointer
本文介绍了C ++映射字符串和成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,所以我做一个地图用字符串作为键和一个成员函数指针作为值。我似乎无法弄清楚如何添加到地图中,这似乎不起作用。
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)
{
}
推荐答案
请参阅 std :: map :: insert
和 value_type
myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));
和 operator []
myMap["test"] = &Test::TestFunc;
不能使用没有对象的成员函数的指针。您可以使用指向成员函数的指针,其类型为 Test对象
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!");
或指向的指针测试
/ p>
or with a pointer to type Test
Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");
另请参见 C ++常见问题 - 指向成员函数的指针
这篇关于C ++映射字符串和成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文