Chinaunix首页 | 论坛 | 博客
  • 博客访问: 64308
  • 博文数量: 15
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 220
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-22 09:09
文章分类

全部博文(15)

文章存档

2009年(15)

我的朋友
最近访客

分类: C/C++

2009-04-24 15:41:41

写下来,备忘:
类似于MFC中的:
// handler.h
#ifndef _HANDLER_H_
#define _HANDLER_H_
#define COMMAND_FIRST 1
#define COMMAND_SECOND 2
#define COMMAND_THIRD 3
class CHandler
{
public:
 CHandler(){}
 ~CHandler(){}
 int Process(int command);
private:
 int OnFirst(int first);
 int OnSecond(int second);
 int OnThird(int third);
private:
 typedef int (CHandler::*PHANDLER)(int id);
 struct HandlerEntry
 {
  char bCommand;
  PHANDLER pHandler;
 };
 static const HandlerEntry m_handlers[];
};
#endif
 
// handler.cpp
#include "handler.h"
#include
const CHandler::HandlerEntry CHandler::m_handlers[] =
{
 {COMMAND_FIRST, &CHandler::OnFirst},
 {COMMAND_SECOND, &CHandler::OnSecond},
 {COMMAND_THIRD, &CHandler::OnThird}
};
int CHandler::Process(int command)
{
 if (command < 0)
 {
  return command;
 }
 const int handlerCount = sizeof(m_handlers) / sizeof(HandlerEntry);
 for (int i = 0; i < handlerCount; ++i)
 {
  if (m_handlers[i].bCommand == command)
  {
   PHANDLER pHandler = m_handlers[i].pHandler;
   return (this->*pHandler)(command);
  }
 }
 return -1;
}
int CHandler::OnFirst(int first)
{
 printf("OnFirst\n");
 return first;
}
int CHandler::OnSecond(int second)
{
 printf("OnSecond\n");
 return second;
}
int CHandler::OnThird(int third)
{
 printf("OnThird\n");
 return third;
}
 
// 调用
#include "handler.h"
#include "compares.h"

int main()
{
 CHandler *pHandler = new CHandler();
 for (int i = -1; i < 4; ++i)
 {
  int result = pHandler->Process(i);
  if (result < 0)
  {
   printf("Bad Command\n");
   continue;
  }
 }
 
 return 0;
}
阅读(1119) | 评论(0) | 转发(0) |
0

上一篇:C++ 回调函数

下一篇:stl find_if

给主人留下些什么吧!~~