一直都对两个概念有所混淆--指针函数与函数指针,下面我们通过两个例子来讲解一下
-----------------------------------------------------------------------------------------------------------------------------------
开始
------------------------------------------------------------------------------------------------------------------------------------
1、指针函数
(1) 基本概念
指针函数:顾名思义就是带有指针的函数,即其本质是一个函数,只不过这种函数返回的是一个对应类型的地址。
(2) 定义式
type *func (type , type)
如:int *max(int x, int y)
(3) 例子详解
- #include <iostream>
- using namespace std;
- int *GetNum(int x); //指针函数声明形式
- void main(void)
- {
- cout<<"===============start================"<<endl;
- int num;
- cout<<"Please enter the number between 0 and 6: ";
- cin>>num;
- cout<<"result is:"<<*GetNum(num)<<endl; //输出返回地址块中的值
- }
- int *GetNum(int x) {
- static int num[]={0,1,2,3,4,5,6};
- return &num[x]; //返回一个地址
- }
总结:从上面的小例子我们可以看出子函数返回的是数组中某一元素所在的地址值,输出的是这一地址中存储的数。
2、函数指针
(1) 基本概念
函数指针:指向函数的指针变量,本质上是一个指针变量
(2) 定义式
type (*func)(type , type )
如:int (*max)(int a, int b)
(3) 例子详解
- #include <iostream>
- using namespace std;
- int max(int a, int b) {
- return a>b?a:b;
- }
- void main(void)
- {
- cout<<"===========start==========="<<endl;
- int (*func)(int,int); //定义一个指向该函数形式的指针变量
- func=max;
- int a,b;
- cout<<"Please enter two numbers:";
- cin>>a>>b;
- int result=(*func)(a,b); //运用指针变量调用函数
- cout<<"max="<<result<<endl;
- }