天天看點

C++ code:函數指針數組

函數指針作為一種資料類型,當然可以作為數組的元素類型。例如,要實作用菜單來驅動函數調用的程式架構,則用函數指針數組來實作就比較容易維護。

1 #include<iostream>
 2 using namespace std;
 3 
 4 typedef void(*MenuFun)();
 5 void f1(){ cout << "good!\n"; }
 6 void f2(){ cout << "better!\n"; }
 7 void f3(){ cout << "best!\n"; }
 8 
 9 int main()
10 {
11     MenuFun fun[] = {f1,f2,f3};
12     for (int choice = 1; choice;)
13     {
14         cout << "1-----display good\n"
15             << "2-----display better\n"
16             << "3-----display best\n"
17             << "0-----display exit\n"
18             << "Enter your choice:";
19         cin >> choice;
20         switch (choice)
21         {
22         case 1:fun[0](); break;
23         case 2:fun[1](); break;
24         case 3:fun[2](); break;
25         case 0:return 0;
26         default:cout << "you entered a wrong key.\n";
27         }
28     }
29 }      
C++ code:函數指針數組

程式第4行首先定義了一個函數指針類型MenuFun。若前面無typedef,則後面部分就是一個函數指針定義,是以,正因為有了typedef,MenuFun就是函數指針的類型名,可以以此建立函數指針,但其本身并不是函數指針。

1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 typedef void(*MenuFun)();
 6 void f1(){ cout << "good!\n"; }
 7 void f2(){ cout << "better!\n"; }
 8 void f3(){ cout << "best!\n"; }
 9 
10 int main()
11 {
12     vector<MenuFun> fun(3);
13     fun[0] = f1, fun[1] = f2, fun[2] = f3;
14     for (int choice = 1; choice;)
15     {
16         cout << "1-----display good\n"
17             << "2-----display better\n"
18             << "3-----display best\n"
19             << "0-----display exit\n"
20             << "Enter your choice:";
21         cin >> choice;
22         if (choice > 0 && choice < 4) fun[choice - 1]();
23         else if (choice == 0) return 0;
24         else cout << "you entered a wrong key.\n";
25     }
26 }      
上一篇: 指針和數組
下一篇: C++函數指針

繼續閱讀