C ++使用函数作为参数 [英] C++ using function as parameter

查看:104
本文介绍了C ++使用函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

假设我有一个函数

void funct2(int a) {

}


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

 ;


}

功能?

推荐答案

通常,为了可读性,您使用typedef来定义自定义类型如下:

Normally, for readability's sake, you use a typedef to define the custom type like so:

typedef void (* vFunctionCall)(int args);

当定义这个typedef时,你想要的函数原型的返回参数类型, (在这种情况下为int args)引导 typedef标识符(在本例中为void类型)和原型参数

when defining this typedef you want the returning argument type for the function prototypes you'll be pointing to, to lead the typedef identifier (in this case the void type) and the prototype arguments to follow it (in this case "int args").

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

When using this typedef as an argument for another function, you would define your function like so (this typedef can be used almost exactly like any other object type):

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

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

and then used like a normal function, like so:

funct2(a);

因此,整个代码示例如下所示:

So an entire code example would look like this:

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;
}

并打印出来:

2

这篇关于C ++使用函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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