C++使用函数作为参数

Mar*_*ark 11 c++

可能重复:
如何在C中将函数作为参数传递?

假设我有一个叫做的函数

void funct2(int a) {

}


void funct(int a, (void)(*funct2)(int a)) {

 ;


}
Run Code Online (Sandbox Code Playgroud)

调用此函数的正确方法是什么?我需要设置什么才能让它工作?

Mat*_*zza 21

通常,为了便于阅读,您使用typedef来定义自定义类型,如下所示:

typedef void (* vFunctionCall)(int args);
Run Code Online (Sandbox Code Playgroud)

在定义此typedef时,您需要为要指向的函数原型返回参数类型,引导 typedef标识符(在本例中为void类型)和跟随它的原型参数(在本例中为"int args") .

当使用这个typedef作为另一个函数的参数时,你可以像这样定义你的函数(这个typedef几乎可以像任何其他对象类型一样使用):

void funct(int a, vFunctionCall funct2) { ... }
Run Code Online (Sandbox Code Playgroud)

然后像普通函数一样使用,如下所示:

funct2(a);
Run Code Online (Sandbox Code Playgroud)

所以整个代码示例如下所示:

typedef void (* vFunctionCall)(int args);

void funct(int a, vFunctionCall funct2)
{
   funct2(a);
}

void otherFunct(int a)
{
   printf("%i", a);
}

int main()
{
   funct(2, (vFunctionCall)otherFunct);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

并打印出来:

2
Run Code Online (Sandbox Code Playgroud)

  • 从C ++ 11开始,人们宁愿使用`vFunctionCall = void(*)(int args);`来提高可读性。甚至更好,使用[std :: function](/sf/ask/1809408331/) (3认同)
  • 无需进行任何铸造。 (2认同)
  • @GoswinvonBrederlow `std::function<void(int)>` 比 `void (*)(int args)` 做的事情*多*,因此平台更难优化 (2认同)

Mar*_*tin 20

另一种方法是使用函数库。

std::function<output (input)>

这里有一个例子,我们将使用funct2inside funct

#include <iostream>
using namespace std;
#include <functional>

void displayMessage(int a) {
    cout << "Hello, your number is: " << a << endl;
}

void printNumber(int a, function<void (int)> func) {
    func(a);
}

int main() {
    printNumber(3, displayMessage);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出 : Hello, your number is: 3