You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++报range-based for loop是C++11扩展和expected expression错误如何解决

解决方案

1. 补全代码缺失内容

原代码缺少必要的标准库头文件引用,且未指定std命名空间,同时调整输出文本匹配你预期的显示效果,修正后的完整代码如下:

#include <iostream>
#include <string>
#include <list>

using namespace std;

class YouTubeChannel {
public:
    string Name;
    string OwnerName;
    int SubsCount;
    list<string> PublishedVideos;
};

int main(){
    YouTubeChannel ytChannel;
    ytChannel.Name = "Wonder World";
    ytChannel.OwnerName = "Sally";
    ytChannel.SubsCount = 1200;
    ytChannel.PublishedVideos = {"Victoria Memorial", "Red Fort", "Monument"};

    cout << "Name : " << ytChannel.Name << endl;
    cout << "Owner Name : " << ytChannel.OwnerName << endl;
    cout << "Subscriber Count : " << ytChannel.SubsCount << endl;
    cout << "Videos : " << endl;
    for(string videoTitle : ytChannel.PublishedVideos){
        cout << videoTitle << endl;
    }
    return 0;
}

2. 指定C++编译标准

你遇到的报错和警告本质是因为初始化列表赋值、范围for循环都是C++11版本才引入的特性,默认编译选项没有开启对应标准支持:

  • 如果你使用g++/clang命令行编译,执行如下命令即可:
    g++ 你的源文件名.cpp -o 输出程序名 -std=c++11
    你也可以指定更高版本的标准,比如-std=c++17,兼容性更好。
  • 如果你使用Visual Studio、CLion、Dev-C等IDE,在项目设置的「C标准」选项中,选择C++11或更高版本即可。

完成以上两步后编译运行,就能得到你预期的输出结果。

内容的提问来源于stack exchange,提问作者Aditi Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:09:03