C++函数指针

函数存放在代码的内存区域内,函数名代表了函数的地址,如:int fun(int a);fun就是函数在内存中的地址。 
1.定义一个指向函数的指针  
以int fun(int a)为例: 
int(*fp)(int a);//定义了一个指向函数的指针. 
注意与int *fp(int a)的区别,  
int *fp(int a);//声明了一个返回int 型指针的函数.
#include<iostream>  
#include<windows.h>  
using namespace std;  
  
int fun(int a)  
{  
    return a;  
}  
int main()  
{  
    cout<<fun<<endl;  
    int(*fp)(int a);  
    fp=fun;  
    cout<<fp(5)<<endl;  
    cout<<(*fp)(10)<<endl;  
    Sleep(1000);  
    return 0;  
  



2.用typedef定义简化函数指针的定义


typedef int(*fp)(int a);  
fp fp1=fun;  
cout<<fp1(5)<<endl;  
cout<<(*fp1)(10)<<endl;</strong></span>  


3.函数指针作为参数传递给函数。


#include<iostream>  
#include<windows.h>  
using namespace std;  
  
int fun(int a)  
{  
    return a;  
}  
int Test(int(*fp)(int),int b)  
{  
    return fp(1)+b;  
}  
int main()  
{  
      
    typedef int(*fp)(int a);  
    fp fpi=fun;  
    cout<<Test(fpi,2)<<endl;  
      
    Sleep(1000);  
    return 0;  
  
}


4.构成指向函数的指针数组
几个名字不同的函数,只要返回类型和参数个数,参数类型一致,就是同一类函数指针。




#include<iostream>  
#include<windows.h>  
using namespace std;  
  
int fun1(int a)  
{  
    return a;  
}  
int fun2(int a)  
{  
    return a+1;  
}  
  
int fun3(int a)  
{  
    return a+2;  
}  
  
int main()  
{  
    typedef int(*fp)(int a);  
    fp b[]={fun1,fun2,fun3};  
    cout<<b[0](1);  
  
    return 0;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值