C 函式指標詳解

2022-09-25 01:18:09 字數 2110 閱讀 8918

1. 獲取函式的位址

2. 宣告乙個函式指標

3.使用函式指標來呼叫函式

獲取函式指標:

函式的位址就是函式名,要將函式作為引數進行傳遞,必須傳遞函式名。

宣告函式指標

宣告指標時,必須指定指標指向的資料型別,同樣,宣告指向函式的指標時,必須指定指標指向的函式型別,這意味著宣告應當指定函式的返回型別以及函式的引數列表。

例如:double cal(int); // prototype

double (*pf)(int); // 指標pf指向的函式, 輸入引數為int,返回值為double

pf = cal; // 指標賦值

如果將指標作為函式的引數傳遞:

void estimate(int lines, double (*pf)(int)); // 函式指標作為引數傳遞

使用指標呼叫函式

double y = cal(5); // 通過函式呼叫

double y = (*pf)(5); // 通過指標呼叫 推薦的寫法

double y = pf(5); // 這樣也對, 但是不推薦這樣寫

函式指標的使用:

#include

#include

#include 程式設計客棧th>

using namespace std;

double cal_m1(int lines)

double cal_m2(int li程式設計客棧nes)

void estimate(int line_num, double (*pf)(int lines))

int main(int argc, char *ar**)

函式指標陣列:

這部分非常有意思:

#include

#include

#include

using namespace std;

// prototype 實質上三個函式的引數列表是等價的

const double* f1(const double arr, in n);

const double* f2(const double , int);

const double* f3(const double* , int);

int main(int argc, char *ar**);

// 宣告指標

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) = ; // 宣告乙個指標陣列,儲存三個函式的位址

cout << "pointer array : " << parray[2](a, 3) << " : " << *(parray[2](a, 3)) << endl;

co程式設計客棧ut << "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)

const double* f2(const double arr, int n)

const double* f3(const double* arr, int n)

這裡可以只用typedef來減少輸入量:

typedef const double* (*pf)(const double , int); // 將pf定義為乙個型別名稱;

pf p1 = f1;

pf p2 = f2;

pf p3 = f3;

C 函式指標的詳解

1.函式指標 1 一般來說函式通常包括一系列指令,通過編譯後,在記憶體中佔據了一塊儲存空間。它有乙個起始位址,這個起始 入口 位址就稱為函式的指標。2 主函式在呼叫子函式時,就是讓程式轉移到函式的入口位址開始執行。3 我們可以定義乙個指標變數用來指向函式,然後通過使用該指標變數呼叫此函式。總結了一下...

指標函式,函式指標,指標的指標 詳解

1 指標函式是指帶指標的函式,即本質是乙個函式。函式返回型別是某一型別的指標 型別識別符號 函式名 參數列 int f x y 首先它是乙個函式,只不過這個函式的返回值是乙個位址值。函式返回值必須用同型別的指標變數來接受,也就是說,指標函式一定有函式返回值,而且,在主調函式中,函式返回值必須賦給同型...

C 函式指標及其作用詳解

查了很多資料,對函式指標已了解。函式指標指向某種特定型別,函式的型別由其引數及返回型別共同決定,與函式名無關。舉例如下 int add int nleft,int nright 函式定義該函式型別為int int,int 要想宣告乙個指向該類函式的指標,只需用指標替換函式名即可 int pf int...