C++实现回调函数

#include <iostream>
#include <string>
#include <map>
#include <string.h>
using namespace std;

class Test
{
public:
    Test()
    {
        m_map.insert(std::pair<string, Call>("add", (Call)&Test::add));
        m_map.insert(std::pair<string, Call>("sub", (Call)&Test::sub));
        m_map.insert(std::pair<string, Call>("mul", (Call)&Test::mul));
    }

    void print(string method, int a, int b)
    {
        Mapit it = m_map.find(method);
        if (it == m_map.end())
        {
            cout << "no find function: " << method << endl;
        }
        else
        {
            (this->*m_map[method])(a, b);
        }
    }

public:
    ///Call是函数指针,有2个int类型的形参和void的返回值
    typedef void (Test::*Call)(int a, int b);

    ///CallMap是map<string, Call>这种数据类型的别名
    ///用CallMap定义了一个成员变量m_map
    typedef map<string, Call> CallMap;
    CallMap m_map;

    ///MapIt是CallMap::iterator这种迭代器的别名
    typedef CallMap::iterator Mapit;

    ///可以将add,sub和mul这三个函数放到m_map中
    void add(int a, int b)
    {
        cout << "a + b = " << a + b << endl;
    }
    void sub(int a, int b)
    {
        cout << "a - b = " << a - b << endl; 
    }

    void mul(int a, int b)
    {
        cout << "a * b = " << a * b << endl;
    }
};

int main()
{
    Test test;
    ///根据字符串找到想对应的函数进行操作
    test.print("add", 2, 1);
    test.print("sub", 2, 1);
    test.print("mul", 2, 2);
    test.print("div", 2, 2);

    return 0;
}
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值