【问题标题】:how to call member function from map of classes如何从类映射中调用成员函数
【发布时间】:2019-12-12 05:45:59
【问题描述】:

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

但我得到了

错误:必须使用'.'或'->'来调用指向成员函数的指针 '((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())) (...)',例如'(...->* ((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' 没有在这个范围内声明

【问题讨论】:

  • 我建议您了解std::functionlambdas(或者可能是std::bind),因为这样会让这样的事情更加更容易。
  • -&gt;*-&gt; 不同——右边的不是成员的名称,而是在当前范围内计算的表达式。

标签: c++ stdmap member-function-pointers


【解决方案1】:

在您尝试过的代码中,p 的类型为 B*。为了访问它的run方法指针你应该写p-&gt;func["run"]而不是p-&gt;*func["run"],最后调用那个方法你应该写p-&gt;*(p-&gt;func["run"])

void doSome() {
    // pointer to the B object
    B* p = myMap["place"];

    // pointer to the method
    B::funcp method_ptr = p->func["run"];

    // invoke the method on the object
    p->*method_ptr(5);
}

【讨论】:

    【解决方案2】:
    B* bptr = myMap["place"];
    (bptr->*(bptr->func["run"]))(5);
    

    现在测试OK,感谢 Sombrero Chicken 修正了错别字。您不需要所有这些括号,但将它们留在里面可能是个好主意。

    你缺少的是你需要你的B 指针两次。一次是在另一个对象中找到映射,一次是使用成员函数指针调用成员函数。

    【讨论】:

    • tnx 你非常喜欢,在我的真实代码中我使用了 shared_ptr 所以我需要改变一点:{auto p = myMap["place"].get(); (p->*(p->func["run"]))(5);}
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2021-04-18
    • 2020-12-04
    • 2012-04-06
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多