简体   繁体   English

如何使用指向成员函数的指针来调用函数

[英]How to call a function using pointer-to-member-function

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(): 现在我想在run()中调用test_func():

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. 无论我尝试哪种组合,我代码的最后一行都不起作用(编译错误)。

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. 请注意,您有2个错误。 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. 请注意,无论您是否在类范围内,唯一的方法就是使用&ClassName::FuncName & 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. 第二个是通过成员函数指针调用成员时,必须明确指定要在其上调用成员函数的对象(在您的情况下为A型)。 In this case you must specify this (and since this is a pointer we use ->* rather than .* ) 在这种情况下,您必须指定this (由于这是一个指针,我们使用->*而不是.*

HTH HTH

采用:

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

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 演示: http : //www.ideone.com/9o8C4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM