函數(shù)指針基礎(chǔ):
1. 獲取函數(shù)的地址
2. 聲明一個(gè)函數(shù)指針
3.使用函數(shù)指針來(lái)調(diào)用函數(shù)
獲取函數(shù)指針:
函數(shù)的地址就是函數(shù)名,要將函數(shù)作為參數(shù)進(jìn)行傳遞,必須傳遞函數(shù)名。
聲明函數(shù)指針
聲明指針時(shí),必須指定指針指向的數(shù)據(jù)類(lèi)型,同樣,聲明指向函數(shù)的指針時(shí),必須指定指針指向的函數(shù)類(lèi)型,這意味著聲明應(yīng)當(dāng)指定函數(shù)的返回類(lèi)型以及函數(shù)的參數(shù)列表。
例如:
1
2
3
|
double cal( int ); // prototype double (*pf)( int ); // 指針pf指向的函數(shù), 輸入?yún)?shù)為int,返回值為double pf = cal; // 指針賦值 |
如果將指針作為函數(shù)的參數(shù)傳遞:
1
|
void estimate( int lines, double (*pf)( int )); // 函數(shù)指針作為參數(shù)傳遞 |
使用指針調(diào)用函數(shù)
1
2
3
|
double y = cal(5); // 通過(guò)函數(shù)調(diào)用 double y = (*pf)(5); // 通過(guò)指針調(diào)用 推薦的寫(xiě)法 double y = pf(5); // 這樣也對(duì), 但是不推薦這樣寫(xiě) |
函數(shù)指針的使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <iostream> #include <algorithm> #include <cmath> using namespace std; double cal_m1( int lines) { return 0.05 * lines; } double cal_m2( int lines) { return 0.5 * lines; } void estimate( int line_num, double (*pf)( int lines)) { cout << "The " << line_num << " need time is: " << (*pf)(line_num) << endl; } int main( int argc, char *argv[]) { int line_num = 10; // 函數(shù)名就是指針,直接傳入函數(shù)名 estimate(line_num, cal_m1); estimate(line_num, cal_m2); return 0; } |
函數(shù)指針數(shù)組:
這部分非常有意思:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#include <iostream> #include <algorithm> #include <cmath> using namespace std; // prototype 實(shí)質(zhì)上三個(gè)函數(shù)的參數(shù)列表是等價(jià)的 const double * f1( const double arr[], int n); const double * f2( const double [], int ); const double * f3( const double * , int ); int main( int argc, char *argv[]) { double a[3] = {12.1, 3.4, 4.5}; // 聲明指針 const double * (*p1)( const double *, int ) = f1; cout << "Pointer 1 : " << p1(a, 3) << " : " << *(p1(a, 3)) << endl; cout << "Pointer 1 : " << (*p1)(a, 3) << " : " << *((*p1)(a, 3)) << endl; const double * (*parray[3])( const double *, int ) = {f1, f2, f3}; // 聲明一個(gè)指針數(shù)組,存儲(chǔ)三個(gè)函數(shù)的地址 cout << "Pointer array : " << parray[2](a, 3) << " : " << *(parray[2](a, 3)) << endl; cout << "Pointer array : " << parray[2](a, 3) << " : " << *(parray[2](a, 3)) << endl; cout << "Pointer array : " << (*parray[2])(a, 3) << " : " << *((*parray[2])(a, 3)) << endl; return 0; } const double * f1( const double arr[], int n) { return arr; // 首地址 } const double * f2( const double arr[], int n) { return arr+1; } const double * f3( const double * arr, int n) { return arr+2; } |
這里可以只用typedef來(lái)減少輸入量:
1
2
3
4
|
typedef const double * (*pf)( const double [], int ); // 將pf定義為一個(gè)類(lèi)型名稱(chēng); pf p1 = f1; pf p2 = f2; pf p3 = f3; |
到此這篇關(guān)于C++函數(shù)指針詳解的文章就介紹到這了,更多相關(guān)C++函數(shù)指針內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/zj1131190425/article/details/92065897