这是我要实现的:
class Delegate
{
public:
void SetFunction(void(*fun)());
private:
void(*mEventFunction)();
}
然后是名为Test的类
class Test
{
public:
Test();
void OnEventStarted();
}
现在在Test()中,我想像这样将OnEventStarted传递给Delegate:
Test::Test()
{
Delegate* testClass = new Delegate();
testClass->SetFunction(this::OnEventStarted);
}
但是OnEventStarted是一个非静态成员函数,该怎么办?
为了调用成员函数,您既需要指向成员函数的指针,又需要对象。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它将void (Test:: *mEventFunction)();
并且Test
仅将其与成员一起使用,更好的解决方案是使用std::function
。这是这样的:
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));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句