C++函數(shù)指針詳解
函數(shù)指針基礎:
1. 獲取函數(shù)的地址
2. 聲明一個函數(shù)指針
3.使用函數(shù)指針來調用函數(shù)
獲取函數(shù)指針:
函數(shù)的地址就是函數(shù)名,要將函數(shù)作為參數(shù)進行傳遞,必須傳遞函數(shù)名。
聲明函數(shù)指針
聲明指針時,必須指定指針指向的數(shù)據(jù)類型,同樣,聲明指向函數(shù)的指針時,必須指定指針指向的函數(shù)類型,這意味著聲明應當指定函數(shù)的返回類型以及函數(shù)的參數(shù)列表。
例如:
double cal(int); // prototype double (*pf)(int); // 指針pf指向的函數(shù), 輸入參數(shù)為int,返回值為double pf = cal; // 指針賦值
如果將指針作為函數(shù)的參數(shù)傳遞:
void estimate(int lines, double (*pf)(int)); // 函數(shù)指針作為參數(shù)傳遞
使用指針調用函數(shù)
double y = cal(5); // 通過函數(shù)調用 double y = (*pf)(5); // 通過指針調用 推薦的寫法 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ù)的參數(shù)列表是等價的
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}; // 聲明一個指針數(shù)組,存儲三個函數(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定義為一個類型名稱; pf p1 = f1; pf p2 = f2; pf p3 = f3;
到此這篇關于C++函數(shù)指針詳解的文章就介紹到這了,更多相關C++函數(shù)指針內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

