函數(shù)指針基礎(chǔ):
- 獲取函數(shù)的地址
- 聲明一個(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ù)列表等限。
例如:
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); // 通過(guò)函數(shù)調(diào)用
double y = (*pf)(5); // 通過(guò)指針調(diào)用 推薦的寫(xiě)法
double y = pf(5); // 這樣也對(duì), 但是不推薦這樣寫(xiě)
函數(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ù)組形娇,存儲(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)減少輸入量:
typedef const double* (*pf)(const double [], int); // 將pf定義為一個(gè)類(lèi)型名稱(chēng);
pf p1 = f1;
pf p2 = f2;
pf p3 = f3;