2013-05-02 99 views
4

我想編譯一些C++代碼(可以用Windows上的Visual Studio 2012編譯)與g++-4.4錯誤:預期初始值設定項之前':'令牌

我有此代碼段,

const std::string cnw::restoreSession(const std::vector<string> &inNwsFile) { 
    for (std::string &nwFile : inNwsFile){ 
     // some... 
    } 
} 

,我不能因爲這個錯誤的編譯:

CNWController.cpp:154: error: expected initializer before ‘:’ token 

你能給我如何解決這個問題的一些建議?

+0

爲什麼在for循環中使用冒號而不是分號? – 0x499602D2 2013-05-02 15:46:06

+3

@ 0x499602D2:因爲這是C++ 11基於範圍的'for'的語法。 – 2013-05-02 15:47:30

回答

12

您的編譯器太老,無法支持基於範圍的for語法。根據GNU,它首次在GCC 4.6中得到支持。 GCC還要求您在編譯器的命令行選項-std=c++11c++0x上顯式請求C++ 11支持。

如果不能升級,那麼你就需要老派相當於:

for (auto it = inNwsFile.begin(); it != inNwsFile.end(); ++it) { 
    std::string const &nwFile = *it; // const needed because inNwsFile is const 
    //some... 
} 

我相信auto是在GCC 4.4可用(只要您啓用的C++ 0x的支持),爲您節省寫作std::vector<string>::const_iterator

如果你真的需要一個非const參考向量的元素的話,所使用的任何循環的風格,你需要從功能參數中刪除const

+2

編譯時他可能還需要'-std = C++ 11'標誌。 – olevegard 2013-05-02 15:55:56

+3

@olevegard:的確,雖然它是一個小寫的'c',而較老的編譯器稱之爲'C++ 0x'。 – 2013-05-02 15:58:29

+0

感謝邁克,它的工作。是的,我必須使用'C++ 0x',我的編譯器不支持'C++ 11'標誌。 – Aslan986 2013-05-02 16:11:24

相關問題