Passing a void function as an argument to another function

╄→гoц情女王★ 提交于 2019-12-08 13:41:07

问题


I'm trying to pass a void function to another void function, unsuccessfully so far. So I created this function inside the class called ExitButton like this. ExitButton.h:

class ExitButton{

 void setup(void (*_setup));

};

Then I include that class into another class like this. ofApp.h:

include "ExitButton.h"
class ofApp : public ofBaseApp{

 void update();
 void setup(); 
 StartButton *startButton;

}

So in my ofApp.cpp I want to call the update function like this:

void ofApp::update(){


exitButton->setup(setup()); // This throws me the following error: Cannot initialize a parameter of type 'void (*)' with an rvalue of type void
    }

So I assume, I can only pass a void function that is a pointer? Is it actually possible to pass a void function as a parameter to another function?


回答1:


This is probably what you want:

#include <iostream>
using namespace std;

class ExitButton{
public:
    void setup(void (*_setup)())
    {    
        _setup(); // we call the function pointer
    };
};    


void setup() // this is a void function
{
    cout << "calling void setup()" << endl;
}

int main()
{
    ExitButton eb;
    eb.setup(setup); // use a void function as a parameter
}


来源:https://stackoverflow.com/questions/25860157/passing-a-void-function-as-an-argument-to-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!