C++使用传递函数

Max*_*ian 7 c++ c++11

我有两个函数,其中一个函数作为一个参数,这工作得很好,但我想在我的第二个函数中调用这个传递的函数.

class XY {   
 public:

   void first(void f());
   void second();        
 };

 void XY::first(void f()){

 }

 void XY::second(){
 f(); //passed function from first()
 }
Run Code Online (Sandbox Code Playgroud)

Edg*_*jān 12

您可以使用std :: function来存储可调用对象并稍后调用它.

class X {
    public:
        void set(std::function<void()> f) {
            callable = f;
        }

        void call() const {
            callable();
        }

    private:
        std::function<void()> callable;
};

void f() {
    std::cout << "Meow" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

然后创建X实例并设置可调用:

X x;
x.set(f);
Run Code Online (Sandbox Code Playgroud)

稍后调用存储的callable:

x.call();
Run Code Online (Sandbox Code Playgroud)

  • upvoted,很棒的c ++ 11答案,我只会提到模板是<functional>标题的一部分 (3认同)