要使 gcc 4.8.1 支持 c++11 中的新"auto"功能?

To make gcc 4.8.1 support the new "auto" feature in c++11?

本文关键字:auto 功能 c++11 gcc 支持 要使      更新时间:2023-10-16

我使用 gcc 4.8.1 编译器来编译我的代码,它使用 auto 的新 c++11 功能。假定 auto 关键字会自动推断数据类型。但是,编译器抛出一个错误:

   *** does not name a type

这是我的代码:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str="If you want to do it, try your best.";
    cout<<str<<endl;
    for(auto i:str){             //<-error here
        cout<<i<<endl;
    }

    return 0;
}

错误是:

'i' does not name a type.....(of course there are some error message following)

我的编译器版本是:gcc version 4.8.1(in MingW)

根据 gcc

文档,这个版本的 gcc 已经支持 c++11,那么为什么会这样呢?

你需要使用 -std=c++11 标志进行编译

例如:

gcc somefile.c -std=c++11