各位,我在对代码重构时,有些函数用switch ,太多的case,现把每个case都拿出来做了一个子函数,但是有人说可以用表驱动法进一步优化,也就是不用switch,本人不太明白,请各位不吝赐教。最好给个例子
解决方案 »
- 为什么程序到这里就死了呢?
- 高手 如何将非主框架类中的数据显示在编辑框中
- 为什么会出现错误?帮看一下代码,谢谢
- 急!!!是否可以用全局钩子进行文件IO读取的过滤,知道的快进!
- MFC的消息处理
- recv()是阻塞函数把? while( cc=recv(ssock,buf,sizeof(buf)-1,0) ){
- VC下的自动换行
- 快过年了,有一个问题大家积极的讨论一下吧:把位图转换成矢量图的算法讨论及可行性分析。顺便散点儿分喽!
- 请问如何在客户区连续画图啊?问题多多,给分多多!
- 调用SetTimer()时出现Debug Assertion Failed!错误
- vc6.0关于消息映射函数 名字空间处理问题
- 关于MFC设计软件的流程
否则用hash表.
// MapTest002.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include "MapTest002.h"
#include <map>#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif/////////////////////////////////////////////////////////////////////////////
// The one and only application objectCWinApp theApp;using namespace std;
void t1(CString str)
{
printf("1"+str);
}
void t2(CString str)
{
printf("2"+str);
}
void t5(CString str)
{
printf("5"+str);
}
void t7(CString str)
{
printf("7"+str);
}
typedef void (* funcT)(CString str);
map<int,funcT> mFun;void switcTest(int i)
{
/*
switch (i)
{
case 1:
t1("1\n");
break;
case 2:
t2("2\n");
break;
case 5:
t5("5\n");
break;
case 7:
t7("7\n");
break;
}
*/
mFun[i]("ff\n");
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0; // initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
//CString strHello;
//strHello.LoadString(IDS_HELLO);
//cout << (LPCTSTR)strHello << endl;
mFun.insert(pair<int,funcT>(1,&t1));
mFun.insert(pair<int,funcT>(2,&t2));
mFun.insert(pair<int,funcT>(5,&t5));
mFun.insert(pair<int,funcT>(7,&t7));
switcTest(5);
} return nRetCode;
}
里面有你需要的这个做法的改进方法。
另外,你这样吧一个switch拆开,也未必就很利于阅读和维护。如果真的就这么简单的结构,那你根本这个方法都多余了。直接用策略模式传递函数指针回调就可以了。