范围 对于循环帮助:令牌之前的预期初始值设定项":"

Range For loop help: Expected initializer before ":" token

本文关键字:于循环 循环 范围 令牌 帮助      更新时间:2023-10-16

我是一个c++新手,我现在正在学习c++入门书。

我写了一个关于字符串的小例子,下面是代码:

#include <iostream>
#include <string>
#include <cctype>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
    string s("Hello World");
    for (auto &c : s)
        c = toupper(c);
    cout << s << endl;
    return 0;
}

我在Linux上使用GCC版本4.4.6,我试图用:

编译这段代码:
g++ test_strings.c -std=c++0x

,但得到以下错误:

test_strings.c: In function 'int main()':
test_strings.c:14: error: expected initializer before ':' token
test_strings.c:19: error: expected primary-expression before 'return'
test_strings.c:19: error: expected ')' before 'return'

我从教科书中复制了程序,所以我认为这是一个拼写错误,但经过检查并尝试在网上搜索并更新我的gcc后,错误提醒。非常感谢您的帮助。

根据GCC中的c++ 0x/c++ 11支持页面,您需要运行GCC 4.6才能获得range-for功能。

4.6更改页面包含:

改进了对即将到来的c++ 0x ISO c++标准的实验支持,包括对constexpr(感谢Gabriel Dos Reis和Jason Merrill)、nullptr(感谢Magnus Fromreide)、noexcept、无限制联合、基于范围的for循环(感谢Rodrigo Rivas Costa)、不透明enum声明(也感谢Rodrigo)、隐式删除函数和隐式move构造函数的支持。