问题如下:考虑这段代码:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a();
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我如何使用a's aClass::test …
c++ arguments function-pointers parameter-passing pointer-to-member
这是我想要意识到的:
class Delegate
{
public:
void SetFunction(void(*fun)());
private:
void(*mEventFunction)();
}
Run Code Online (Sandbox Code Playgroud)
然后是名为Test的类
class Test
{
public:
Test();
void OnEventStarted();
}
Run Code Online (Sandbox Code Playgroud)
现在在 Test() 中,我想像这样将 OnEventStarted 传递给委托:
Test::Test()
{
Delegate* testClass = new Delegate();
testClass->SetFunction(this::OnEventStarted);
}
Run Code Online (Sandbox Code Playgroud)
但是 OnEventStarted 是一个非静态成员函数,我该怎么办?