TICPP CHAPTER 11 EX 27 & EX28

/* 27. Start with FunctionTable.cpp from Chapter 3. Create a class that contains a vector of pointers to functions, with add( ) and remove( ) member functions to add and remove pointers to functions. Add a run( ) function that moves through the vector and calls all of the functions. */ //: C03:FunctionTable.cpp #include <iostream> #include <vector> using namespace std; // A macro to define dummy functions: #define DF(N) void N() { /    cout << "function " #N " called..." << endl; } DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g); class FuncTable {     vector<void(*)()>ft; public:     void add(void(*f)()) {         ft.push_back(f);     }     void remove(){         ft.pop_back();     }     void run() {         for (int i = 0; i < ft.size(); i++) {             //看清楚調用格式 ,有無*號都可以              (*ft[i])();         }     } }; //void (*func_table[])() = { a, b, c, d, e, f, g }; int main() {     FuncTable test;     test.add(&a);     test.add(&b);     test.run();     test.remove();     cout << "after b() is removed" << endl;     test.run(); } ///:~

 

//28. Modify the above Exercise 27 so that it works with //pointers to member functions instead. //: C03:FunctionTable.cpp #include <iostream> #include <vector> using namespace std; // A macro to define dummy functions:      #define DF(N) void N() { /    cout << "function X::" #N " called..." << endl; } #define MAKEX / class X{ / public: /     DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g); / } //定義了一個X類  MAKEX; class FuncTable {     vector<void(X::*)()>ft; public:     void add(void(X::*f)()) {         ft.push_back(f);     }     void remove(){         ft.pop_back();     }     void run(X& x) {        //需要傳入一個X類對象,否則無法調用          for (int i = 0; i < ft.size(); i++) {             //看清楚調用格式 ,必須有*號              (x.*ft[i])();         }     } }; //void (*func_table[])() = { a, b, c, d, e, f, g }; int main() {     X x;     FuncTable test;     test.add(&X::a);     test.add(&X::b);     test.run(x);     test.remove();     cout << "after X::b() is removed." << endl;     test.run(x); } ///:~
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章