更新时间:2023-01-08 08:21:29
要调用成员函数,既需要指向成员函数的指针,又需要对象。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它为 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));
}