Ram*_*lol 8 c c++ pointers function-pointers
我问了一些具体的问题.
对于问题2,这是我的意思:
void s(void) {
//...
}
void f(function) { // what should I put as type to pass a function as an argument
//...
}
f(s);
Run Code Online (Sandbox Code Playgroud)
Jac*_*kin 24
要定义函数指针,请使用以下语法:
return_type (*ref_name) (type args, ...)
Run Code Online (Sandbox Code Playgroud)
因此,要定义一个名为"doSomething"的函数引用,它返回一个int并接受一个int参数,你可以这样写:
int (*doSomething)(int number);
Run Code Online (Sandbox Code Playgroud)
然后,您可以将引用分配给实际函数,如下所示:
int someFunction(int argument) {
printf("%i", argument);
}
doSomething = &someFunction;
Run Code Online (Sandbox Code Playgroud)
完成后,您可以直接调用它:
doSomething(5); //prints 5
Run Code Online (Sandbox Code Playgroud)
因为函数指针本质上只是指针,所以你确实可以在类中使用它们作为实例变量.
当接受函数指针作为参数时,我更喜欢使用a typedef而不是使用函数原型中的混乱语法:
typedef int (*FunctionAcceptingAndReturningInt)(int argument);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用此新定义的类型作为函数的参数类型:
void invokeFunction(int func_argument, FunctionAcceptingAndReturningInt func) {
int result = func(func_argument);
printf("%i", result);
}
int timesFive(int arg) {
return arg * 5;
}
invokeFunction(10, ×Five); //prints 50
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |