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

后端 未结 2 2060
-上瘾入骨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: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 fn) { mEventFunction = fn);
    private:
        std::function fn;
    }
    
    Test::Test() {
        Delegate testClass; // No need for dynamic allocation
        testClass->SetFunction(std::bind(&Test::OnEventStarted, this));
    }
    

提交回复
热议问题