C++ Pointers to functions
#include <iostream>
using namespace std;
void hello()
{
cout << "hello ";
}
void world()
{
cout << "world! ";
}
void show(void(*fun)())
{
(*fun)();
}
int main()
{
void(*pfunc2hello)() = hello;
void(*pfunc2world)() = world;
show(pfunc2hello);
show(pfunc2world);
}
Run
hello world! 请按任意键继续. . .
Note
声明函数指针
void(*pfunc2hello)() = hello;
- 声明一个函数指针,命名为
pfunc2hello
void
是被指向的函数的返回值类型,在上面的代码里是voidhello
是自己定义的一个函数的函数名
以函数指针作为参量
void show(void(*fun)())
{
(*fun)();
}
- 定义一个函数
show
- 接受一个函数指针(pointers to functions)作为参量(parameter),这个函数指针叫做
fun
(*fun)();
运行fun
所指向的函数
运行函数
show(pfunc2hello);
- main()函数中读取函数指针运行函数
总结
func_re_type (*def_func_ptr_name)(T a1, T a2, ...) = def_func_name
Reference
C++ Language//Compound data types//Pointers//Pointers to functions
http://www.cplusplus.com/doc/tutorial/pointers/