我正在尝试通过成员函数 ptr 的映射来调用成员函数 那是不同类的数据成员
{
class B
{
public:
typedef void (B::*funcp)(int);
B()
{
func.insert(make_pair("run",&B::run));
}
void run(int f);
map<string,funcp>func;
};
class A
{
public:
A();
void subscribe(B* b)
{
myMap["b"] = b;
}
map<string,B*>myMap;
void doSome()
{
myMap["place"]->func["run"](5);
}
};
int main()
{
A a;
B b;
a.subscribe(&b);
a.doSome();
return 0;
}
}
但是我得到了
error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((A*)this)->A::myMap.std::map, B*>::operator[](std::basic_string(((const char*)"place"), std::allocator()))->B::func.std::map, void (B::)(int)>::operator[](std::basic_string(((const char)"run"), std::allocator())) (...)’, e.g. ‘(... ->* ((A*)this)->A::myMap.std::map, B*>::operator[](std::basic_string(((const char*)"place"), std::allocator()))->B::func.std::map, void (B::)(int)>::operator[](std::basic_string(((const char)"run"), std::allocator()))) (...)’
我也试过了:
{
auto p = myMap["place"];
(p->*func["run"])(5);
}
然后修正错误:
‘func’ was not declared in this scope
最佳答案
B* bptr = myMap["place"];
(bptr->*(bptr->func["run"]))(5);
OK 现在测试通过了,感谢 Sombrero Chicken 修正了拼写错误。您不需要所有这些括号,但将它们留在里面可能是个好主意。
您缺少的是您需要两次 B
指针。一次在另一个对象中找到映射,一次使用成员函数指针调用成员函数。
关于c++ - 如何从类映射调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346108/