如何使用指针到成员函数调用函数 [英] How to call a function using pointer-to-member-function
问题描述
我有一个类:
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];
};
现在我想在run()中调用test_func():
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.
推荐答案
使用:
void A::run()
{
test_case[0].test_func = &A::test_func_0;
(this->*(test_case[0].test_func))(1);
}
请注意,您有2个错误。第一个是你如何形成成员函数指针。注意,唯一的方法是使用& ClassName :: FuncName
,无论你是否在类范围。 &
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.
第二个是当你通过一个成员函数指针调用一个成员时,你必须明确指定对象(你的case中的类型A)其中调用成员函数。在这种情况下,你必须指定 this
(因为这是一个指针,我们使用 - > *
c $ c>。* )
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
这篇关于如何使用指针到成员函数调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!