回调函数的实现(指向类成员函数的指针)

参考《C和C++代码精粹》——Chunk Allison

菜单实现

#include <iostream>
using namespace std;

class Object
{
public:
    void retrieve() {cout << "Object::retrieve\n";}
    void insert() {cout << "Object::insert\n";}
    void update() {cout << "Object::update\n";}
    void process(int choice);
    
private:
    static void (Object::*farray[3])();
};

void (Object::*Object::farray[3])()=
{
    &Object::retrieve,
    &Object::insert,
    &Object::update
};

void Object::process(int choice)
{
    if (0 <= choice && choice <= 2)
    {
        (this->*farray[choice])();
    }
} 

int main()
{
    int show_menu(void);
    Object o;
    for (;;)
    {
        int choice = show_menu();
        cout << "choice=" << choice << endl;
        if (1<=choice && choice <= 3)
        {
            o.process(choice-1);
        }
        else if (choice == 4)
        {
            break;
        }
    }
    return 0;
}

int show_menu(void)
{
    cout << "==================MENU===================" << endl;
    cout << "1. retrieve" << endl;
    cout << "2. insert" << endl;
    cout << "3. update" << endl;
    cout << "4. exit" << endl;
    cout << "please input witch number you choose:";
    char input;
    cin>>input;
    return input-'0';
}

运行效果

image

使用typedef使指向成员函数的指针更清晰

#include <iostream>
using namespace std;

class Object
{
public:
    void retrieve() {cout << "Object::retrieve\n";}
    void insert() {cout << "Object::insert\n";}
    void update() {cout << "Object::update\n";}
    void process(int choice);
    
private:
    typedef void (Object::*Omf)();
    static Omf farray[3];
//    static void (Object::*farray[3])();
};

Object::Omf Object::farray[3] = 
//void (Object::*Object::farray[3])()=
{
    &Object::retrieve,
    &Object::insert,
    &Object::update
};

void Object::process(int choice)
{
    if (0 <= choice && choice <= 2)
    {
        (this->*farray[choice])();
    }
} 

int main()
{
    int show_menu(void);
    Object o;
    for (;;)
    {
        int choice = show_menu();
        cout << "choice=" << choice << endl;
        if (1<=choice && choice <= 3)
        {
            o.process(choice-1);
        }
        else if (choice == 4)
        {
            break;
        }
    }
    return 0;
}

int show_menu(void)
{
    cout << "==================MENU===================" << endl;
    cout << "1. retrieve" << endl;
    cout << "2. insert" << endl;
    cout << "3. update" << endl;
    cout << "4. exit" << endl;
    cout << "please input witch number you choose:";
    char input;
    cin>>input;
    return input-'0';
}
原文地址:https://www.cnblogs.com/hanxi/p/2682051.html