C++函數(shù)指針詳解
函數(shù)指針基礎(chǔ):
1. 獲取函數(shù)的地址
2. 聲明一個(gè)函數(shù)指針
3.使用函數(shù)指針來調(diào)用函數(shù)
獲取函數(shù)指針:
函數(shù)的地址就是函數(shù)名,要將函數(shù)作為參數(shù)進(jìn)行傳遞,必須傳遞函數(shù)名。
聲明函數(shù)指針
聲明指針時(shí),必須指定指針指向的數(shù)據(jù)類型,同樣,聲明指向函數(shù)的指針時(shí),必須指定指針指向的函數(shù)類型,這意味著聲明應(yīng)當(dāng)指定函數(shù)的返回類型以及函數(shù)的參數(shù)列表。
例如:
double cal(int); // prototype double (*pf)(int); // 指針pf指向的函數(shù), 輸入?yún)?shù)為int,返回值為double pf = cal; // 指針賦值
如果將指針作為函數(shù)的參數(shù)傳遞:
void estimate(int lines, double (*pf)(int)); // 函數(shù)指針作為參數(shù)傳遞
使用指針調(diào)用函數(shù)
double y = cal(5); // 通過函數(shù)調(diào)用 double y = (*pf)(5); // 通過指針調(diào)用 推薦的寫法 double y = pf(5); // 這樣也對, 但是不推薦這樣寫
函數(shù)指針的使用:
#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ù)組:
這部分非常有意思:
#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ù)組,存儲三個(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來減少輸入量:
typedef const double* (*pf)(const double [], int); // 將pf定義為一個(gè)類型名稱; pf p1 = f1; pf p2 = f2; pf p3 = f3;
到此這篇關(guān)于C++函數(shù)指針詳解的文章就介紹到這了,更多相關(guān)C++函數(shù)指針內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
QT網(wǎng)絡(luò)通信TCP客戶端實(shí)現(xiàn)詳解
這篇文章主要為大家詳細(xì)介紹了QT網(wǎng)絡(luò)通信TCP客戶端實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08純c語言實(shí)現(xiàn)面向?qū)ο蠓治雠c示例分享
采用C語言實(shí)現(xiàn)的關(guān)鍵是如何運(yùn)用C語言本身的特性來實(shí)現(xiàn)多態(tài)、繼承面、封裝的面向?qū)ο蟮奶卣?最近給出了例子,大家可以參考使用2014-01-01Matlab利用prim算法實(shí)現(xiàn)迷宮的生成
普里姆算法(Prim算法),圖論中的一種算法,可在加權(quán)連通圖里搜索最小生成樹。本文將利用prim算法迷宮生成及其藝術(shù)渲染,感興趣的可以了解一下2022-10-10