2016-06-13 20 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

メンバ関数を呼び出すには、メンバ関数へのポインタとオブジェクトの両方が必要です。ただし、メンバー関数の型に実際に関数を含むクラスが含まれている場合(例では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()のような機能を実行するために、Testクラスのインスタンスを取得する必要があります

関連する問題