C++ 创建一个函数,像一个变量,稍后改变它的主体,然后再调用它

C++ Creating a function, like a variable, change its body later and then call it later

我正在尝试在 class 中创建一个虚拟函数,稍后将在 int main() 中更改其函数体。然后我想在 class 中调用这个 body changed func。有办法实现吗?

像这样:

class Animation {
public:

    //Don't know what to write at the next line
    function<void>/*?*/ whenCompleted = []() mutable { /* Dummy func. */ };
    .
    .
    .
    void startAnimation() { /* Do stuff, then */ animationEnded(); }
    void animationEnded() { whenCompleted(); }

}score;


int main(){
    score.whenCompleted = { /* new body for whenCompleted() */ }
    score.startAnimation();
}

你的想法基本上是对的

#include <functional>
#include <iostream>
 
class Animation
{
public:
    std::function<void()> whenCompleted;
 
    void startAnimation() { animationEnded(); }
    void animationEnded() { whenCompleted(); }
};
 
int main()
{
    Animation score;
    score.whenCompleted = [](){ std::cout << "all done"; };
    score.startAnimation();
}

output

all done

您还可以为 Animation 添加一个构造函数,它接受一个函数来初始化 whenCompleted

Animation(std::function<void()>&& onCompleted) : whenCompleted(onCompleted) {}

这会将 main 修改为

int main()
{
    Animation score{[](){ std::cout << "all done"; }};
    score.startAnimation();
}