How to call a function using pointer-to-member-function

感情迁移 提交于 2020-01-11 11:25:07

问题


I have a class:

class A {
    void test_func_0(int);
    void run();

    typedef void(A::*test_func_t)(int);

    struct test_case_t{
       test_func_t test_func;
    } test_case[100];
};

Now I want to call test_func() inside run():

void A::run() 
{
    test_case[0].test_func = &test_func_0;
    test_case[0].*(test_func)(1);
}

The last line of my code, doesn't work(compile error), no matter what combination I try.


回答1:


Use this:

void A::run() 
{   
    test_case[0].test_func = &A::test_func_0;
    (this->*(test_case[0].test_func))(1);
}

Notice that you had 2 errors. The first one was how you formed the member-function-pointer. Note that the only way to do it is to use &ClassName::FuncName regardless of whether you're at class scope or not. & is mandatory too.

The second is that when you call a member via a member function pointer, you must explicitly specif y the object (of type A in your case) on which to call the member function. In this case you must specify this (and since this is a pointer we use ->* rather than .*)

HTH




回答2:


Use:

(this->*test_case[0].test_func)(1);



回答3:


Member function call using pointer-to-member-function:

 test_case[0].test_func = &A::test_func_0; //note this also!
(this->*test_case[0].test_func)(1);

Demo : http://www.ideone.com/9o8C4



来源:https://stackoverflow.com/questions/5218903/how-to-call-a-function-using-pointer-to-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!