C++下的单例模式以及map的用法

使用wizard生成.h及.cpp

  1. #include <string>
  2. #include <map>
  3. using namespace std;
  4. class Tool
  5. {
  6. protected:
  7.     Tool();
  8. public:
  9.     static Tool* getInstance();
  10. public:
  11.     string getDescription(short id);
  12. private:
  13.     static map<short,string> dictionary;
  14. private:
  15.     static Tool* instance ;
  16. };
  1. #include "stdafx.h"
  2. #include "CommonUtils.h"
  3. #include <map>
  4. #include <string>
  5. //#include <utility>
  6. using namespace std;
  7. map<short,string> Tool::dictionary;//定义map对象
  8. Tool* Tool::instance=0;//对.h中的静态参量进行赋值
  9. Tool::Tool()
  10. {
  11.     //使用pair向map中填充<key,value>值对
  12.     dictionary.insert(pair<short,string>(1,"value"));
  13.     
  14. }
  15. Tool* Tool::getInstance(){
  16.     if (0==instance)
  17.     {
  18.         instance = new Tool;
  19.     }
  20.     return instance;
  21. }
  22. string Tool::getDescription(short id){
  23.         //必须使用<short,string>进行指定模板参数,才能使用后续的second
  24.     std::map<short,string>::iterator it =dictionry.find(id);
  25.     return (*it).second;
  26. }
哎,C++的入门啊,搞了3个小时

洗洗,睡了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值