c++ - 如何从类映射调用成员函数

标签 c++ stdmap pointer-to-member

我正在尝试通过成员函数 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/

相关文章:

Linux 和 Windows 之间的 C++ std::map 差异

c++ - 映射到方法 c++11

c - 指针指向指针以避免重复代码?

C++——这里是否存在从 Fred* 到 auto_ptr<Fred> 的隐式转换?

c++ - 在整个硬盘中查找文件

c++ - 使用静态函数在类中存储非静态对象

c++ - 指向具有不同编译器的成员函数的指针

c++ - 实现类似值的复制赋值运算符

c++ - std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数

C++ 在两个 std::map 之间查找匹配项的有效方法