【问题标题】:populating map globally在全球范围内填充地图
【发布时间】:2011-06-02 03:13:53
【问题描述】:

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

   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")));

它显示错误,如 error C2143: syntax error : missing ';'在第 2 行的 '.' 之前。

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

【问题讨论】:

    标签: c++ stl initialization global-variables static-initializer


    【解决方案1】:

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

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

    [更新]

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

    【讨论】:

    • 不,这不能解决问题。应该使用来自 C++0x 的初始化列表或在构造函数中填充基类的继承类。您不能在全局范围内执行任意函数,只能执行全局对象的构造函数或初始化程序。
    • @Vlad 你说的这个继承的类在构造函数中填充基是什么意思
    • @Vlad 我认为您实际上应该单独回答。
    【解决方案2】:

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

    由于您在模板中使用&gt;&gt;,因此您的编译器必须足够新才能支持 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

    【讨论】:

    • 即使这样可行,它也不会告诉 OP 为什么他的代码被破坏了。
    • 我使用的是 Vs 2008,不支持 C++0x。
    • 我认为VS2008在这方面不符合标准,因为它愿意接受这样的&gt;&gt;s。
    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 2020-07-11
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多