C++ 使用函数作为参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6339970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ using function as parameter
提问by Mark
Possible Duplicate:
How do you pass a function as a parameter in C?
可能的重复:
如何在 C 中将函数作为参数传递?
Suppose I have a function called
假设我有一个名为
void funct2(int a) {
}
void funct(int a, (void)(*funct2)(int a)) {
;
}
what is the proper way to call this function? What do I need to setup to get it to work?
调用此函数的正确方法是什么?我需要设置什么才能让它工作?
回答by Matt Razza
Normally, for readability's sake, you use a typedef to define the custom type like so:
通常,为了可读性,您使用 typedef 来定义自定义类型,如下所示:
typedef void (* vFunctionCall)(int args);
when defining this typedef you want the returning argument type for the function prototypes you'll be pointing to, to leadthe typedef identifier (in this case the void type) and the prototype arguments to followit (in this case "int args").
在定义此 typedef 时,您希望将指向的函数原型的返回参数类型引导typedef 标识符(在本例中为 void 类型)和跟随它的原型参数(在本例中为“int args”) .
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):
当使用这个 typedef 作为另一个函数的参数时,你可以像这样定义你的函数(这个 typedef 几乎可以像任何其他对象类型一样使用):
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;
}
and would print out:
并会打印出:
2
回答by Tatvamasi
check this
检查这个
typedef void (*funct2)(int a);
void f(int a)
{
print("some ...\n");
}
void dummy(int a, funct2 a)
{
a(1);
}
void someOtherMehtod
{
callback a = f;
dummy(a)
}