函数指针如何工作?

Ram*_*lol 8 c c++ pointers function-pointers

我问了一些具体的问题.

  1. 如何在课堂上初始化它们?
  2. 如何将函数作为参数传递?
  3. 是否需要在类中声明和定义函数指针?

对于问题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, &timesFive); //prints 50
Run Code Online (Sandbox Code Playgroud)

  • @Luis G. Costantini R.:你需要`&`for pointers-to-members(ISO 14882:2003 C++ Standard 5.3.1/3).我个人在所有情况下都使用`&`来表示我实际上是在传递一个函数指针. (12认同)
  • @ sil3nt:函数指针是在C兼容的公共API**中具有回调函数**的方法.但是,在C++模块中,指向具有适当虚函数的抽象类的指针要灵活得多. (5认同)
  • 您不需要&获取函数的地址. (3认同)
  • @ sil3nt:在C中,可以使用函数指针来模拟你在C++中使用虚函数做的事情.也就是说,你的"对象"可以是带有一组指向函数的指针的结构或数组,然后不同的"类"可以将自己的"方法"指针放入这些插槽中.另一种用途是用于事件驱动的"回调"类型的设计. (2认同)