/*
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); }
///
:~