Thursday, January 26, 2012

Function Pointer

變數有pointer,函式也有!

#include <iostream>

using namespace std;

int bigger(int, int);
int smaller(int, int);
int find(int, int, int(*)(int, int));

int main(){

 int a, b;
 cout << "a=";
 cin >> a;
 cout << "b=";
 cin >> b;

 // find the bigger one
 cout << find(a, b, bigger) << endl;

 // find the smaller one
 cout << find(a, b, smaller) << endl;

 return 0;
}

int find(int a, int b, int(*compare)(int a, int b)){
 return (*compare)(a, b);
}

int bigger(int a, int b){
 return (a>b)?a:b;
}

int smaller(int a, int b){
 return (a<b)?a:b;
}

No comments:

Post a Comment