生活 + 筆記

4.24.2010

C++ function pointer

function pointer

int (*fn1)(int);
fn1 function pointer 可以指向所有使用一個整數參數(int)及回傳整數的函式int

int square(int a){ return a*a; }

int cubic(int a){ return a*a*a; }

int (*foo)(int); //foo function pointer

foo = square; //將foo指向square函式

cout << foo(2) << endl; //執行foo(2)等於執行square(2) foo = cubic; cout << foo(3) << endl; //執行foo(3)等於執行cubic(3)

使用function pointer主要目的是讓函式可以當成參數傳入另一個函式

int sum(int (*fp)(int), int a, int b){

int s = 0;

for(int i=0; i<=b; i++) s+=fp(i); }

cout << sum(square, 1, 3) << endl; //計算square(1)+...square(3)

cout << sum(cubic, 1, 5) << endl; //計算cubic(1)+...square(5)


如此只要依照傳入的function不同而有不同的behavior
不用特別寫兩個function來處理

沒有留言:

張貼留言