Arrays of pointers to functions

Arrays of pointers to functions
One of the more interesting constructs you can create is an array of 
pointers to fuArrays of pointers to functionsnctions. To select a function, you just index into the 
array and dereference the pointer. This supports the concept of 
table-driven code; instead of using conditionals or case statements, 
you select functions to execute based on a state variable (or a 
combination of state variables). This kind of design can be useful if 
you often add or delete functions from the table (or if you want to 
create or change such a table dynamically). 
The following example creates some dummy functions using a 
preprocessor macro, then creates an array of pointers to those 
functions using automatic aggregate initialization. As you can see, 
it is easy to add or remove functions from the table (and thus, 
functionality from the program) by changing a small amount of 
code: 
//: C03:FunctionTable.cpp 
// Using an array of pointers to functions 
#include <iostream> 
3: The C in C++   217 
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); 
void (*func_table[])() = { a, b, c, d, e, f, g }; 
int main() { 
while(1) { 
cout << "press a key from 'a' to 'g' " 
"or q to quit" << endl; 
char c, cr; 
cin.get(c); cin.get(cr); // second one for CR 
if ( c == 'q' ) 
break; // ... out of while(1) 
if ( c < 'a' || c > 'g' ) 
continue; 
(*func_table[c - 'a'])(); 

} ///:~ 
At this point, you might be able to imagine how this technique 
could be useful when creating some sort of interpreter or list 
processing program
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值