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); } ///:~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值