理解C/C++函数指针

一、函数的类型与地址

看看下面典型的函数:

int func(){
    return 5;
}
  • func的函数类型:无参且返回类型为int
    • 代码表示:int (*someotherfunc)()

如果函数有两个形参且返回值为bool型呢?函数类型该怎么用代码表示?

bool (*someotherfunc)(int,int)

和变量一样,函数在内存中有固定的地址。函数的实质也是内存中一块固定的内存。

std::cout<<func;    //008A1483
std::cout<<reinterpret_cast<void*>(func); //008A1483

二、函数指针

该怎么写一个指向函数的指针?

int (*funcptr)();         //写法一
int (* const funcptr)();  //写法二:表示funcptr指向的函数的返回值是常量

把一个函数赋值给函数指针:

int foo(){
    return 5;
}
int goo(){
    return 6;
}
int main()
{
    int (*fooptr)() = foo;  //funcptr指向函数foo
    int (*gooptr)() = goo;  //gooptr指向函数goo
    // 如果写成 funptr = goo();   //这是把goo函数的返回值赋值给了funcptr
    return 0;
}

三、通过函数指针调用函数

int foo(int x){
    return x;
}
int main()
{
    int (*funcptr)(int) = foo;
    (*funcptr)(5);  //方式一:通过funcptr调用foo(5)
    funcptr(5);     //方式二:通过funcptr调用foo(5)
    return 0;
}
    

四、把函数作为函数传入另一个函数

int add(int a, int b){
    return a+b;
}
int sub(int a, int b){
    return a-b;
}
void foo(int a, int b, int(*funcptr)(int,int))
{
    cout<<funcptr(a,b)<<endl;
}

int main()
{
    foo(5,3,add);  // 8
    foo(5,3,sub);  // 2
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值