函数指针使用例子

本文介绍了一个使用C++实现的成员函数映射示例。通过定义一个类`TestClass`,该类中包含了一个类型为成员函数指针的映射`m_funcMap`,并演示了如何将成员函数与整数键关联起来,以及如何通过键来调用相应的成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef __TEST_CLASS_H__
#define __TEST_CLASS_H__

#include <map>

class TestClass
{
typedef void (TestClass::*Func) (int);

public:

    TestClass();

    ~TestClass();

    void Run();

protected:

    void TestFirstFunc(int num);

    void TestSecondFunc(int num);

private:

    std::map<int,Func> m_funcMap;

};



#include <iostream>
#include "TestClass.h"

TestClass::TestClass()
{
    m_funcMap.insert(std::make_pair<int,Func>(11,&TestClass::TestFirstFunc));

    m_funcMap.insert(std::make_pair<int,Func>(22,&TestClass::TestSecondFunc));
}

TestClass::~TestClass()
{

}

void TestClass::Run()
{
    Func pfun = m_funcMap[11];
    (this->*pfun) (0);

    (this->*m_funcMap[11]) (1);
    (this->*m_funcMap[22]) (2);

    (this->*m_funcMap[11])  (3);
    (this->*m_funcMap[22])  (4);
}

void TestClass::TestFirstFunc(int num)
{
    std::cout<<"TestFirstFunc="<<num<<std::endl;
}

void TestClass::TestSecondFunc(int num)
{
    std::cout<<"TestSecondFunc="<<num<<std::endl;
}


#include <iostream>
#include "TestClass.h"

using namespace std;

int main()
{
    TestClass mytest;

    mytest.Run();

    return 0;
}

运行结果:

TestFirstFunc=0
TestFirstFunc=1
TestSecondFunc=2
TestFirstFunc=3
TestSecondFunc=4



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值