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

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值