Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1038956
  • 博文数量: 264
  • 博客积分: 6005
  • 博客等级: 大校
  • 技术积分: 2798
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-08 20:15
文章分类

全部博文(264)

文章存档

2011年(42)

2010年(213)

2009年(4)

2008年(2)

2007年(3)

分类: C/C++

2010-12-02 15:28:53

在上一篇,我转载了《C++中指向类成员的指针》, 这是本篇的内容是本篇的基础。
本片文章主要是用实例说明怎样通过map来调用类的成员函数。
场景: 比如说我想通过输入不同的 字符串 然后调用不同的函数来处理。 我想这类应用非常多吧。 而却大部分c++程序员的解决方案是
string   stInput;

if (stInput == "aaa")
{
    // call A function, do something.
}
else if (stInput == "bbb")
{
    / call B function, do something.
}

我们可以看出这样的代码有多丑。今天我们通过map的映射调用函数。
我们可以看一下这样的结构
class  A
{
public:
    ...

public:
   typedef int (A::*pFun_t)(int x);
   mappFun_t>  m_map2Func;
};

这样我们就可以直接通过 key 找到需要调用的成员函数。 是不是很过瘾。
//=====例子, 我这里使用的是 qt 编写的测试程序,需要的可以修改成纯c++的代码======
我的文件和类命名都是用L开头的, 因为L是我们公司的第一个字母。


// !   head file
#ifndef LTEST_H
#define LTEST_H

#include 
#include 

using namespace std;

class LTest
{
public:
    LTest();

public:

    int HelloWorld(int v) // v means value
    {
        cout << "IN helloWorld! a= " << v << endl;
        return 1;
    }


public:

    typedef  int (LTest::*pFunc)(int v);
    QMap<int, pFunc >       m_key2FunPtr;
};

#endif // LTEST_H


// ================ cpp  file ==============
#include "ltest.h"

LTest::LTest()
{
    m_Func.insert(5, &LTest::HelloWorld);
}



// ! main.cpp
#include
#include "ltest.h"





int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    LTest test;
     
    // ! 直接通过key 调用函数, 激动吧。 
    (test.*(test.m_Func[5]))(6); // ! 新手如果看不懂这句,可以分两边来,见下面的方法.

    // ! ==== 这三句是写给新手看的,免得一下转不过弯。 和上面一句是同样的意思
    typedef  int (LTest::*fp)(int);
    fp  p = test.m_Func[5];;
   (test.*p)(1000);
    //===============================



    return a.exec();
}

阅读(1864) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-05 15:12:35

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com