close
函式指標(function pointer)
一、簡介
function本身在記憶體中也佔有一份空間,而function的名稱正是指向此空間的一個參考名稱,當我們呼叫此function時,程式就會去執行此函式名稱指向的memory空間中的指令。
而作為程式設計師,我們也可宣告一個function pointer來指向相同的空間。
二、宣告方法
回傳型態(*指標名稱)(傳遞參數)=欲指向的函式名稱;
三、範例
#include<iostream>
using namespace std;
int fun();
int main() {
int (*ptr)() = fun;
int addr1 = (int)fun; //addr1=12652904
int addr2 = (int)ptr; //addr2=12652904
fun(); //印出"hello"
ptr(); //印出"hello"
return 0;
}
int fun() {
cout<<"hello"<
此範例中的ptr為一指標變數,指向回傳為int且傳入參數為空的function。
接下來看另一個範例:
typedef bool (*CMP)(int, int); void swap(int &, int &); bool larger(int a, int b); bool smaller(int a, int b); void sort(int *arr, int length, CMP); int main() { int arr[] = {2, 7, 9, 1}; sort(arr, 4, larger); //排序後arr為{9,7,2,1} sort(arr, 4, smaller); //排序後arr為{1,2,7,9} return 0; } void swap(int &a, int &b){ int t = a; a = b; b = t; } bool larger(int a, int b){ return a>b; } bool smaller(int a, int b){ return a>b; } void sort(int *arr, int length, CMP compare){
for(int i=0;i<length-1;i++){
for(int j=0;j<length-i-1;j++){
if(compare(arr[j+1],arr[j])){
swap(arr[j+1],arr[j]);
}
}
}
}
此範例中我們使用了typedef來創造一個新的資料型態名為CMP ,是一個可宣告變數為指向回傳值為bool且傳入參數為(int,int)的函式。
參考網址:
http://computer-learning-note.blogspot.tw/2013/08/pointer-to-functionaka-function-pointer.html
http://monkeycoding.com/?p=922
文章標籤
全站熱搜