下面隨筆說明函式指標用法,
函式指標的定義:
定義形式:
存盤型別 資料型別 (*函式指標名)()
含義:
函式指標指向的是程式代碼存盤區
函式指標的典型用途-----實作函式回呼
通過函式指標呼叫的函式
例如將函式的指標作為引數傳遞給一個函式,使得在處理相似事件的時候可以靈活的使用不同的方法,
呼叫者不關心誰是呼叫者
需知道存在一個具有特定原型和限制條件的被呼叫函式,
函式指標舉例
1 #include <iostream> 2 3 using namespace std; 4 5 int compute(int a, int b, int(* func)(int, int)) 6 { 7 return func(a, b); 8 } 9 10 int max(int a, int b) //求最大值 11 { 12 return ((a > b) ? a : b); 13 } 14 15 int min(int a, int b) //求最小值 16 { 17 return ((a < b) ? a : b); 18 } 19 20 int sum(int a, int b) //求和 21 { 22 return (a + b); 23 } 24 25 int main(void) 26 { 27 int a, b, res; 28 29 cout << "please input integer a:"; 30 cin >> a; 31 32 cout << "please input integer b:"; 33 cin >> b; 34 35 res = compute(a, b, &max); //輸入max也可以,max也是表示地址 36 37 res = compute(a, b, &min); //輸入min也可以,min也是表示地址 38 39 res = compute(a, b, &sum); //輸入sum也可以,sum也是表示地址 40 41 return 0; 42 }
本文連接:https://www.cnblogs.com/iFrank/p/14444636.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263230.html
標籤:其他
上一篇:Java 模擬資料庫連接池的實作
