C++ 函數指針

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int PrintVal(int i){
 5     cout<<i<<endl;
 6     return 0;
 7 }
 8 
 9 int Add(int i,int j){
10     return i+j;
11 }
12 
13 void Compare(int i,int j){
14     if(i==j)
15         cout<<i<<"=="<<j<<endl;
16     else if(i>j)
17         cout<<i<<">"<<j<<endl;
18     else
19         cout<<i<<"<"<<j<<endl;
20 }
21 typedef int(*pFunc)(int);
22 
23 int main(){
24     pFunc p1 = PrintVal;
25     int (*p2)(int,int);
26     p1(7);
27     p1 = &PrintVal;
28     (*p1)(8);
29     p2 = Add;
30     cout<<p2(4,5)<<endl;
31 
32     p2 = reinterpret_cast<int(*)(int,int)>(Compare);//進行強轉
33 
34     p2(4,5);
35 }

一、書寫方式 type (*name)(param);ios

二、函數指針書寫比較複雜,通常使用typedef來簡化。函數

三、函數原型必須與定義函數指針時的原型一致,不然會致使編譯錯誤。可是,在某些特殊狀況下,能夠使用reinterpret_cast運算在不一樣類型的函數指針間進行轉換。spa

四、有一種函數叫作「回調函數」。回調函數是一個定義了函數的原型,函數體則交由第三方來實現的一種動態應用模式。在實現函數調用時,先將回調函數的地址做爲參數之一傳遞給主調函數。在主調函數內部經過函數指針調用回調函數。回調函數的機制打破了主調函數與被掉函數靜態綁定的限制,爲用戶提供一種充分利用操做系統的方便手段。操作系統

相關文章
相關標籤/搜索