指向函数的指针数组(C++)

我们能够创建一个指向函数的指针数组。为了选择一个函数,只需要使用数组的下标,然后间接引用这个指针。这种方式支持表格式驱动码的概念;可以根据状态变量去选择被执行函数,而不用条件语句或case语句。这种设计方式对于经常从表中添加或删除函数(或者想动态的创建或改变表)十分有用。

#include <iostream>
using namespace std;
#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);
        if (c == 'q')
            break;
        if (c < 'a' || c > 'g')
            continue;
        (*func_table[c - 'a'])();
    }
    system("pause");
}
原文地址:https://www.cnblogs.com/yongssu/p/4362280.html