为什么Visual Studio社区2022编译我的C++代码?

发布于 2025-02-08 11:36:19 字数 548 浏览 0 评论 0原文

在我的程序中,我有以下代码,并以某种方式编译,但不应该。

#include <list>
#include <iostream>

int main(int argc, char* argv[])
{
    std::list<int> collection = { 1, 2, 3, 4, 5, 6 };

    for each (auto i in collection)
    {
        std::cout << i;
    }

    return 0;
}

我从auto-completion获得了此代码:

for ever(集合中的自动项目)< /code>

我在开发人员PowerShell中使用以下命令来编译我的代码:

cl /ehsc /std:c ++ 17。\ programm.cpp

请帮助我。我不知道为什么会发生这种情况,当我试图在Internet上搜索它时,我发现的只是它没有编译的问题。

In my program, I have the following code, and somehow it compiles, but it shouldn't.

#include <list>
#include <iostream>

int main(int argc, char* argv[])
{
    std::list<int> collection = { 1, 2, 3, 4, 5, 6 };

    for each (auto i in collection)
    {
        std::cout << i;
    }

    return 0;
}

I got this code from auto-completion:

for each (auto item in collection)

I use the following command in the Developer Powershell to compile my code:

cl /EHsc /std:c++17 .\programm.cpp

Please help me. I have no idea why this happens, and when I am trying to search for it on the Internet, all I find are problems where it doesn't compile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的心境我的脸 2025-02-15 11:36:19

每个循环是C ++语言的Microsoft特定扩展名:

,,

通过数组或收集迭代。此非标准关键字在C ++/CLI和本机C ++项目中均可使用。但是,不建议使用它。考虑使用标准 range - 基于语句(C ++)而不是。

...

语法

 每个(expression中的键入标识符){
  语句
}
 

这就是为什么代码在Visual Studio中编译的原因。它不会在任何其他C ++编译器中编译。

A for each loop is a Microsoft-specific extension to the C++ language:

for each, in

Iterates through an array or collection. This non-standard keyword is available in both C++/CLI and native C++ projects. However, its use isn't recommended. Consider using a standard Range-based for Statement (C++) instead.

...

Syntax

for each ( type identifier in expression ) {
  statements
}

That is why the code compiles in Visual Studio. It will not compile in any other C++ compiler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文