这是我想要意识到的:
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 是一个非静态成员函数,我该怎么办?
为了调用成员函数,您需要指向成员函数和对象的指针。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它将仅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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |