error: expected initializer before ‘:’ token

时光总嘲笑我的痴心妄想 提交于 2019-12-10 16:35:37

问题


I am trying to compile some C++ code (which can be compiled with Visual Studio 2012 on Windows) with g++-4.4.

I have this snippet of code,

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

that I cannot compile because of this error:

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

Can you give me some advise on how to solve this problem?


回答1:


Your compiler is too old to support range-based for syntax. According to GNU it was first supported in GCC 4.6. GCC also requires you to explicitly request C++11 support, by giving the command-line option -std=c++11, or c++0x on compilers as old as yours.

If you can't upgrade, then you'll need the old-school equivalent:

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

I believe auto is available in GCC 4.4 (as long as you enable C++0x support), to save you writing std::vector<string>::const_iterator.

If you really do need a non-const reference to the vector's elements then, whichever style of loop you use, you'll need to remove the const from the function parameter.



来源:https://stackoverflow.com/questions/16342285/error-expected-initializer-before-token

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!