2011-06-02 68 views
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

編譯器可能會被第1行的>>弄糊塗(因爲它看起來像是一個移位操作符)。嘗試在裏面插入空格:

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

[更新]

見弗拉德拉扎連科對爲什麼這不會真正解決您的問題發表評論。最簡單的解決方法是將這個工具包裝在一個對象中,在構造函數中初始化它,然後在全局範圍聲明一個。 (但如果你可以避免它,因爲全局變量是邪惡的......)

+4

不,這不會解決它。應使用C++ 0x中的初始化程序列表或構造函數中的繼承類填充基礎。您不能在全局範圍內執行任意函數,只能執行全局對象或初始化器的構造函數。 – 2011-06-02 03:19:33

+0

@Vlad:我停止閱讀語法錯誤...好點。 – Nemo 2011-06-02 03:24:03

+0

@Vlad你應該使用這個在構造函數中繼承的類填充基類的意思 – 2011-06-02 03:25:50

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,其不具有的C++ 0x初始化截至2010年,所以儘量升壓初始化語法來代替:

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

+0

即使這可行,它也不會告訴OP爲什麼他的代碼被破壞了。 – 2011-06-02 03:27:55

+0

@Billy ONeal:編輯 – Cubbi 2011-06-02 03:44:08

+0

我正在使用Vs 2008和C++ 0x不支持。 – 2011-06-02 03:48:43