C ++如何将成员函数指针传递给另一个类?
这就是我要实现的:
class Delegate
{
public:
void SetFunction(void(*fun)());
private:
void(*mEventFunction)();
}
然后是名为Test的类
Then is the class named Test
class Test
{
public:
Test();
void OnEventStarted();
}
现在在Test()中,我想像这样将OnEventStarted传递给Delegate:
Now in Test(), I want to pass OnEventStarted to Delegate like this:
Test::Test()
{
Delegate* testClass = new Delegate();
testClass->SetFunction(this::OnEventStarted);
}
但是OnEventStarted是一个非静态成员函数,该怎么办? / p>
But OnEventStarted is a non-static member function, how should I do?
要调用成员函数,既需要指向成员函数的指针,又需要对象。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它为 void(Test :: * mEventFunction)();
并可以与仅 Test
成员,更好的解决方案是使用 std :: function
。这是这样的: / p>
In order to call a member function, you need both pointer to member function and the object. However, given that member function type actually includes the class containting the function (in your example, it would be void (Test:: *mEventFunction)();
and would work with Test
members only, the better solution is to use std::function
. This is how it would look like:
class Delegate {
public:
void SetFunction(std::function<void ()> fn) { mEventFunction = fn);
private:
std::function<void ()> fn;
}
Test::Test() {
Delegate testClass; // No need for dynamic allocation
testClass->SetFunction(std::bind(&Test::OnEventStarted, this));
}