将字符串映射到函数

Sep*_*deh -1 c++ map

我正在尝试执行此操作,但它不起作用,这是我的错误:

必须使用'。'或'-> '调用'((test *)this)-> test :: mapping.std :: map <_Key,_Tp,_Compare,_Alloc> :: operator []中的指针成员函数(test :: *)(int),std :: less>,std :: allocator,void(test :: *)(int)>>>((((const key_type)(&str))))(... )”,例如“(...-> *((test *)this)-> test :: mapping.std :: map <_Key,_Tp,_Compare,_Alloc> :: operator [],void(test :: *)(int),std :: less>,std :: allocator,void(test :: *)(int)>>>((((const key_type)(&str))))(...)'

test.h:

#include....
using namespace std;
class test
{
    public:
       std::map<std::string, void(test::*)(int)> mapping;
    void Add(int);
};

test.cpp:

test::test()
{
   mapping["Add"]=&test::Add;
   string str = "Add";
   this.*mapping[str](3);// dosnt work!!!!
}

void test::Add(int a)
{
   cout<<a<<endl;
}
Run Code Online (Sandbox Code Playgroud)

不要工作,请帮助我。

jla*_*ahd 5

作为this指针,您需要使用->*而不是.*。此外,需要一些括号。

(this->*mapping[str])(3);
Run Code Online (Sandbox Code Playgroud)

  • @didierc是必要的,因为标准对此表示了要求,如标准中的[expr.call] p1中所述。 (2认同)