函數指針從名子上看就知道它也是一種指針,一個指向函數入口地址的指針,舉個簡單的例子來看看函數指針的用法。
1、通過函數指針調用函數。
[cpp] #include <stdio.h>
#include <stdlib.h>
int Sum(int a, int b)
{
return a + b;
}
int Sub(int a, int b)
{
return a - b;
}
int main(int argc, char *argv[])
{
int iTmp = 0;
int (*pf)(int, int); /*申明一個函數指針,它帶有兩個整形參數,返回一個整形*/
pf = Sum; /*函數指針賦值,使其指向函數Sum*/
iTmp = pf(20, 10); /*調用*/
printf("Sum is : %d\n", iTmp);
pf = Sub; /*使其指向函數Sub*/
iTmp = pf(20, 10); /*調用*/
printf("Sub is : %d\n", iTmp);
system("PAUSE");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int Sum(int a, int b)
{
return a + b;
}
int Sub(int a, int b)
{
return a - b;
}
int main(int argc, char *argv[])
{
int iTmp = 0;
int (*pf)(int, int); /*申明一個函數指針,它帶有兩個整形參數,返回一個整形*/
pf = Sum; /*函數指針賦值,使其指向函數Sum*/
iTmp = pf(20, 10); /*調用*/
printf("Sum is : %d\n", iTmp);
pf = Sub; /*使其指向函數Sub*/
iTmp = pf(20, 10); /*調用*/
printf("Sub is : %d\n", iTmp);
system("PAUSE");
return 0;
}
運行結果:
[plain]
Sum is : 30
Sub is : 10
請按任意鍵繼續. . .
Sum is : 30
Sub is : 10
請按任意鍵繼續. . .
2、函數指針做另一個函數的參數。
[cpp]
#include <stdio.h>
#include <stdlib.h>
int Sum(int a, int b)
{
return a + b;
}
int Sub(int a, int b)
{
return a - b;
}
/*定義函數指針類型*/
typedef int (*pfFun)(int, int);
/*帶有函數指針參數的函數*/
int TestFun(int a, int b, pfFun pf)
{
int i = 0;
i = pf(a, b);
return i;
}
int main(int argc, char *argv[])
{
int iTmp = 0;
iTmp = TestFun(20, 10, Sum); /*函數指針賦值為函數Sum*/
printf("Tmp is: %d\n", iTmp);
iTmp = TestFun(20, 10, Sub); /*函數指針賦值為指針Sub*/
printf("Tmp is: %d\n", iTmp);
system("PAUSE");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int Sum(int a, int b)
{
return a + b;
}
int Sub(int a, int b)
{
return a - b;
}
/*定義函數指針類型*/
typedef int (*pfFun)(int, int);
/*帶有函數指針參數的函數*/
int TestFun(int a, int b, pfFun pf)
{
int i = 0;
i = pf(a, b);
return i;
}
int main(int argc, char *argv[])
{
int iTmp = 0;
iTmp = TestFun(20, 10, Sum); /*函數指針賦值為函數Sum*/
printf("Tmp is: %d\n", iTmp);
iTmp = TestFun(20, 10, Sub); /*函數指針賦值為指針Sub*/
printf("Tmp is: %d\n", iTmp);
system("PAUSE");
return 0;
}運行結果:
[plain]
Tmp is: 30
Tmp is: 10
請按任意鍵繼續. . .
Tmp is: 30
Tmp is: 10
請按任意鍵繼續. . .
第二種用法就是傳說中的回調函數。
摘自 Socrates的專欄