C++函式指標記錄
阿新 • • 發佈:2021-10-01
1 #include <iostream> 2 using namespace std; 3 #include <conio.h> 4 5 int max(int x, int y); //求最大數 6 int min(int x, int y); //求最小數 7 int add(int x, int y); //求和 8 void process(int i, int j, int (*p)(int a, int b)); //應用函式指標 9 10 int main() 11 { 12 int x, y; 13 cin>>x>>y;14 15 cout<<"Max is: "; 16 process(x, y, max); 17 18 cout<<"Min is: "; 19 process(x, y, min); 20 21 cout<<"Add is: "; 22 process(x, y, add); 23 24 getch(); 25 return 0; 26 } 27 28 int max(int x, int y) 29 { 30 return x > y ? x : y; 31 }32 33 int min(int x, int y) 34 { 35 return x > y ? y : x; 36 } 37 38 int add(int x, int y) 39 { 40 return x + y; 41 } 42 43 void process(int i, int j, int (*p)(int a, int b)) 44 { 45 cout<<p(i, j)<<endl; 46 }
這份程式碼,應該是網上找的,非常清晰的關於函式指標的例子。
1 #include<iostream> 2#include "windows.h" 3 using namespace std; 4 int main() 5 { 6 typedef void (*Hello)(); 7 HMODULE hMod = LoadLibrary("test.dll"); 8 if(hMod!=NULL) 9 { 10 Hello hello = (Hello)GetProcAddress(hMod,"test");//void test(); 可以理解為取test()函式地址 11 hello(); 12 cout<<"載入成功"; 13 } 14 else 15 { 16 cout<<"載入失敗"; 17 } 18 }
載入動態庫的時候,也是使用函式指標的方式。
1 #include<iostream> 2 #include "windows.h" 3 using namespace std; 4 5 void he() 6 { 7 MessageBox(0, "Hello World from DLL!\n","Hi",MB_ICONINFORMATION); 8 } 9 int main() 10 { 11 typedef void (*Hello)(void (*p)()); 12 HMODULE hMod = LoadLibrary("test.dll"); 13 if(hMod!=NULL) 14 { 15 Hello hello = (Hello)GetProcAddress(hMod,"test");//呼叫dll的時候,也可以傳個函式地址過去,在dll裡面執行 16 hello(&he); 17 cout<<"載入成功"; 18 while(true){ 19 } 20 } 21 else 22 { 23 cout<<"載入失敗"; 24 } 25 }
呼叫dll也是可以傳遞函式指標的。