C++ 指针函数和函数指针

1、指针函数

(1)基本概念

指针函数:顾名思义就是带有指针的函数,即其本质是一个函数,只不过这种函数返回的是一个对应类型的地址。

(2)定义式

type  *func(type , type)

如:int *max(int x, int y)

(3)例子详解

[cpp] view plain copy

1.   #include <iostream>  

2.   using namespace std;  

3.     

4.     

5.   int *GetNum(int x); //指针函数声明形式  

6.     

7.     

8.   void main(void)  

9.   {  

10.     cout<<"===============start================"<<endl;  

11.     int num;  

12.     cout<<"Please enter the number between 0 and 6: ";  

13.     cin>>num;  

14.     cout<<"result is:"<<*GetNum(num)<<endl;    //输出返回地址块中的值  

15. }  

16.   

17. int *GetNum(int x) {  

18.     static int num[]={0,1,2,3,4,5,6};  

19.     return &num[x];  //返回一个地址  

20. }  

总结:从上面的小例子我们可以看出子函数返回的是数组中某一元素所在的地址值,输出的是这一地址中存储的数。

2、函数指针

(1)基本概念

函数指针:指向函数的指针变量,本质上是一个指针变量

(2)定义式

type (*func)(type ,type )

如:int (*max)(int  a, int  b)

(3)例子详解

[cpp] view plain copy

1.   #include <iostream>  

2.   using namespace std;  

3.     

4.   int max(int a, int b) {  

5.       return a>b?a:b;  

6.   }  

7.     

8.   void main(void)  

9.   {  

10.     cout<<"===========start==========="<<endl;  

11.     int (*func)(int,int);       //定义一个指向该函数形式的指针变量  

12.     func=max;  

13.     int a,b;  

14.     cout<<"Please enter two numbers:";  

15.     cin>>a>>b;  

16.     int result=(*func)(a,b);    //运用指针变量调用函数  

17.     cout<<"max="<<result<<endl;  

18. }  

总结:两者主要区别,一个是函数(指针函数),一个是指针变量(函数指针)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值