将void函数作为参数传递给另一个函数 [英] Passing a void function as an argument to another function

查看:1126
本文介绍了将void函数作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个void函数传递给另一个void函数,迄今为止失败。所以我在这个名为ExitButton的类中创建了这个函数。 ExitButton.h:

  class ExitButton {

void setup(void(* _setup));

};

然后我将这个类包含到另一个类中。 ofApp.h:

  includeExitButton.h
class ofApp:public ofBaseApp {

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






$ b因此在我的app.cpp中,我想调用更新函数是这样的:

  void ofApp :: update(){


exitButton- >设置(设置()); //这会引发以下错误:无法初始化类型为void(*)的参数,其类型为void
}

所以我假设,我只能传递一个void函数,它是一个指针?
实际上是否可以将一个void函数作为参数传递给另一个函数?

解决方案

想要:

  #include< iostream> 
使用namespace std;
$ b $ class ExitButton {
public:
void setup(void(* _setup)())
{
_setup(); //我们调用函数指针
};
};


void setup()//这是一个无效函数
{
cout<< 调用void setup()<< ENDL;
}

int main()
{
ExitButton eb;
eb.setup(setup); //使用void函数作为参数
}


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?

解决方案

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
}

这篇关于将void函数作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆