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. }??
總結:兩者主要區別,一個是函數(指針函數),一個是指針變量(函數指針)。
總結
以上是生活随笔為你收集整理的C++ 指针函数和函数指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ this
- 下一篇: C++ cin.sync()和cin.i