C++中函数指针以及函数指针数组的简单使用

最近复习C++,突然看到函数指针,由于自己上学期C++学习的比较水,所以在这里专门总结一下。 与普通的指针相似,指向函数的指针包含内存中该函数的地址。对比数组,数组名实际是数组的第一个元素在内存中的地址。类似的,函数名实际上是这个函数代码在内存中的开始地址。另外,一定要注意,函数指针要用 type (*FunctionPtr) 的形式,不要写成 type *FunctionPtr的形式,后者表示返回一个所指类型的指针。

上代码:
include <iostream>

using namespace std;

void Function();

void testFunction(void (*)());

int main()

{

    testFunction(Function);

    return 0;

}

void Function()

{

    cout<<"你好!";

}

void testFunction(void (*Function)())

{

    (*Function)();//一定要注意,这里的()不要省略!
}

函数指针数组理解起来就比较容易,但是要注意,数组所指向的所有函数都要有相同类型的返回值和相同的参数类型

看代码:
include <iostream>



using namespace std;

void function0(int);

void function1(int);

void function2(int);

int main()

{

   void (*Function[3])(int) = {function0,function1,function2};

   int choice;

   cout<<"enter a number between 0 to 2,and you can enter 3 to end"<<endl;

   cin>>choice;

   while(choice>=0&&choice<=2)

   {

       (*Function[choice])(choice);

       cout<<"continue"<<endl;

       cin>>choice;

   }

    return 0;

}

void function0(int a)

{

    cout<<"You chose function0 and entered  "<<a<<endl;

}

void function1(int a)

{

    cout<<"You chose function1 and entered "<<a<<endl;

}

void function2(int a)

{

    cout<<"You chose function2 and entered "<<a<<endl;

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值