[C++]C++ Pointers to functions 函数指针

来源:互联网 发布:宁波淘宝开店培训机构 编辑:程序博客网 时间:2024/05/22 02:09

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 是被指向的函数的返回值类型,在上面的代码里是void
  • hello是自己定义的一个函数的函数名

以函数指针作为参量

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/

0 0
原创粉丝点击