gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:03 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com