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. }
总结:两者主要区别,一个是函数(指针函数),一个是指针变量(函数指针)。