0

我已经在全球范围内声明了以下地图并尝试在全球范围内填充。

   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));

它显示错误,如错误 C2143:语法错误:缺少“;” 前 '。' 在第 2 行。

1 我做错了什么
2. 为什么我们不能全局初始化地图。

4

2 回答 2

4

编译器可能对第 1 行感到困惑>>(因为它看起来像一个移位运算符)。尝试在其中插入一个空格:

typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList;

[更新]

请参阅 Vlad Lazarenko 的评论,了解为什么这实际上不能解决您的问题。最简单的解决方法是将这个装置包装在一个对象中,在构造函数中对其进行初始化,然后在全局范围内声明一个。(但如果你能避免它就不会,因为全局变量首先是邪恶的......)

于 2011-06-02T03:17:27.403 回答
2

只有声明和定义可以在全局范围内,并且对 map::insert() 的调用不是其中之一。

由于您>>在模板中使用,因此您的编译器必须足够新才能支持 C++0x。

然后尝试 C++0x 初始化语法:

typedef std::map<unsigned short, std::pair<char,std::string>> DeviceTypeList;
DeviceTypeList g_DeviceTypeList = {
              {(unsigned short)SINGLE_CELL_CAMERA, {'B',"Single Cell Camera"}}
           };

测试:https ://ideone.com/t4MAZ

尽管诊断表明它是 MSVS,它在 2010 年没有 C++0x 初始化程序,因此请尝试使用 boost 初始化程序语法:

typedef std::map<unsigned short, std::pair<char,std::string> > DeviceTypeList;
DeviceTypeList g_DeviceTypeList =
           boost::assign::map_list_of((unsigned short)SINGLE_CELL_CAMERA,
                                       std::make_pair('B',"Single Cell Camera"));

测试:https ://ideone.com/KB0vV

于 2011-06-02T03:25:55.793 回答