你可以传递一个功能,以便以后可以调用它吗?

TPR*_*mus 3 c++ class function object

我希望对象有一个调用函数的方法(但每个对象应该有一个不同的函数来调用).我将通过展示一个例子来向您展示我的意思:

class Human
{
    public:
        void setMyFunction(void func);  // specify which function to call
        void callMyFunction();  // Call the specified function
};

void Human::setMyFunction(void func)    // ''
{
    myFunction = func;
}

void Human::callMyFunction()    // ''
{
    myFunction();
}

void someRandomFunction()   // A random function
{
    // Some random code
}

int main()
{
    Human Lisa;     // Create Object
    Lisa.setMyFunction();   // Set the function for that object
    Lisa.callMyFunction();  // Call the function specified earlier
}
Run Code Online (Sandbox Code Playgroud)

这个代码(显然)不起作用,但我希望你理解我想要完成的事情.

MfG,TPRammus

Jar*_*d42 5

你可能会用std::function.

#include <functional>

class Human
{
    std::function<void()> mFunc;
public:
    void setMyFunction(std::function<void()> func) { mFunc = func; }
    void callMyFunction() { if (mFunc) mFunc(); }
};
Run Code Online (Sandbox Code Playgroud)

演示