2016-06-13 233 views
1

这里是我想要实现什么:C++如何将成员函数指针传递给另一个类?

class Delegate 
{ 
public: 
    void SetFunction(void(*fun)()); 
private: 
    void(*mEventFunction)(); 
} 

然后是命名类测试

class Test 
{ 
public: 
    Test(); 
    void OnEventStarted(); 
} 

现在测试(),我想通过OnEventStarted要委派这样的:

Test::Test() 
{ 
    Delegate* testClass = new Delegate(); 
    testClass->SetFunction(this::OnEventStarted); 
} 

但是OnEventStarted是一个非静态成员函数,该怎么办?

+0

[Do not。](https://isocpp.org/wiki/faq/pointers-to-members#memfnptr-vs-fnptr) – crashmstr

回答

4

为了调用成员函数,您需要指向成员函数和对象的指针。然而,考虑到成员函数类型实际上包括类containting功能(在你的榜样,这将是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)); 
} 
+1

C11中有一个新的'std :: mem_fn',我相信那更好。 –

0

你应该通过&Test::OnEventStarted,这是一个成员函数指针

在这之后,你必须得到测试类的一个实例来运行这样

instanceOfTest->*mEventFunction()功能正确的语法