G不编译基于C 0x范围的循环

前端之家收集整理的这篇文章主要介绍了G不编译基于C 0x范围的循环前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用G的一些新的C 0x功能. Lambdas,auto和其他新功能就像一个魅力,但基于范围的for循环无法编译.这是我测试的程序:
#include <iostream>
#include <vector>

int main ()
{
    std::vector<int> data = { 1,2,3,4 };

    for ( int datum : data )
    {
        std::cout << datum << std::endl;
    }
}

我编译它:

g++ test.cpp -std=c++0x

我也试过gnu 0x,但输出是一样的.

这是输出

test.cpp: In function ‘int main()’:
test.cpp:8:21: error: expected initializer before ‘:’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘;’ before ‘}’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘)’ before ‘}’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘;’ before ‘}’ token

在此先感谢您的帮助.

编辑:我正在使用GCC版本4.5.2,我现在看到它太旧了.

解决方法

您需要GCC 4.6及更高版本才能获得基于范围的for循环.

GCC’s C++0x status

$cat for.cpp
#include <iostream>
int main()
{
  for (char c: "Hello,world!")
    std::cout << c;
  std::cout << std::endl;
  return 0;
}
$g++ -std=c++0x -o for for.cpp
$./for
Hello,world!
$g++ --version
g++ (GCC) 4.6.1 20110325 (prerelease)
原文链接:https://www.f2er.com/c/116196.html

猜你在找的C&C++相关文章