C++ How to pass member function pointer to another class?

后端 未结 2 2052
-上瘾入骨i
-上瘾入骨i 2020-12-19 15:22

Here is what I want to realize:

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

Then i

相关标签:
2条回答
  • 2020-12-19 15:39

    You should pass &Test::OnEventStarted, this is the right syntax for a member function pointer

    And after that, you'll have to get an instance of the Test class to run the function like this

    instanceOfTest->*mEventFunction()

    0 讨论(0)
  • 2020-12-19 15:44

    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));
    }
    
    0 讨论(0)
提交回复
热议问题