错误:':'令牌之前期望的初始化项

error: expected initializer before ‘:’ token

本文关键字:初始化 期望 令牌 错误      更新时间:2023-10-16

我正试图用g++-4.4编译一些c++代码(可以在Windows上使用Visual Studio 2012编译)。

我有这段代码,
const std::string cnw::restoreSession(const std::vector<string> &inNwsFile) {
   for (std::string &nwFile : inNwsFile){
       // some...
   }
}

,我不能编译,因为这个错误:

CNWController.cpp:154: error: expected initializer before ‘:’ token
你能就如何解决这个问题给我一些建议吗?

您的编译器太旧,无法支持基于范围的for语法。根据GNU的说法,它最初是在GCC 4.6中支持的。GCC还要求您显式地请求c++ 11支持,通过在与您一样老的编译器上提供-std=c++11c++0x命令行选项。

如果你不能升级,那么你需要旧的等效:

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的引用来指向vector的元素,那么,无论你使用哪种类型的循环,你都需要从函数形参中删除const