使用直接大括号初始化时,C++ 编译错误“预期”;“在声明末尾”)

c++ compile error 'expected ';' at end of declaration' when using direct brace initialization

提问人:M. Layton 提问时间:6/20/2020 最后编辑:M. Layton 更新时间:8/15/2022 访问量:9614

问:

我是 C++ 的新手,正在学习我的第一个教程,当我尝试编译课程中的代码时,出现以下错误:

expected ';' at end of declaration
    int x{ }; // define variable x to hold user input (a...
         ^
         ;

我尝试运行的程序的完整代码:

#include <iostream>  // for std::cout and std::cin
 
int main()
{
    std::cout << "Enter a number: ";
    int x{ }; 
    std::cin >> x; 
    std::cout << "You entered " << x << '\n';
    return 0;
}

我在 Macbook Pro 上使用 Visual Studio Code (v.1.46.1),带有 Microsoft C/C++扩展名 (https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools)。

我的编译器是 Clang:

Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

最初,我在 VS Code 中运行终端>配置默认生成任务来创建 .vscode/tasks.json 编译器设置文件。该文件目前如下所示:

{
    "version": "2.0.0",
    "tasks": [
    {
      "type": "shell",
      "label": "C/C++: clang++ build active file",
      "command": "/usr/bin/clang++",
      "args": [
        // Set C++ Standards 
        "-std=c++17",

        // Increase compiler warnings to maximum
        "-Wall",
        "-Weffc++",
        "-Wextra",
        "-Wsign-conversion",

        // Treat all warnings as errors
        "-Werror",

        // Disable compiler extensions
        "-pedantic-errors",

        // File to compile
        "-g",
        "${file}",

        // Output file
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

我设置了标志,根据我的理解,它应该允许直接大括号初始化。-std=c++17

我不确定这是否重要,因为我正在尝试编译而不是构建/调试,但为了彻底起见,我还有一个包含以下内容的 .vscode/launch.json 文件:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "clang++ - Build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}",
      "args": [],
      "stopAtEntry": true,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "lldb",
      "preLaunchTask": "C/C++: clang++ build active file"
    }
  ]
}

有人可以帮我弄清楚为什么不能正常工作以初始化变量以及我可以做些什么来修复它以使其正常工作吗?int x{ };

[编辑]:我检查/测试了其他设置:

  • 直接从命令行运行 compile 时,代码可以正确编译clang++ -std=c++17 -g helloworld.cpp -o helloworld
  • VS Code C/C++ 扩展配置将“C++ 标准”设置为 c++17(似乎是默认值)。即便如此,在不设置标志的情况下运行命令行编译也会导致相同的编译器错误。-std=c++17
  • 尝试更改为以下内容:int x{ };
    • int x( );:失败并显示一长串错误
    • int x(0);:编译成功
    • int x = { };:编译成功
    • int x = {0};:编译成功
    • 'int x;': 编译成功
    • 'int x = 0;': 编译成功
C++ 可视化 Studio 代码 编译器错误 C++17

评论

0赞 ChrisMM 6/20/2020
你能在命令行上编译它吗,还是也会产生错误?
0赞 Nate Eldredge 6/20/2020
源文件的名称是什么,包括扩展名?clang 从文件名中推断出语言,它可能认为这是 C++ 以外的东西。另外,除了显示的错误之外,还有其他错误吗?
0赞 M. Layton 6/20/2020
@ChrisMM是的,它确实使用'''从命令行编译 clang++ -std=c++17 -Wall -Weffc++ -Wextra -Wsign-conversion -Werror -pedantic-errors -g helloworld.cpp -o helloworld ''' 当我删除命令行上的所有可选标志时,它也能很好地编译,如下所示: ''' clang++ -std=c++17 -g helloworld.cpp -o helloworld '''
0赞 M. Layton 6/20/2020
@NateEldredge源文件称为 。这是我遇到的唯一错误。完整的控制台输出为: ''' 正在执行的任务: /usr/bin/clang++ -g /Users/{已编辑}/Documents/development/c++/learncpp/helloworld/helloworld.cpp -o /Users/{已编辑}/Documents/development/c++/learncpp/helloworld/helloworld < /Users/{已编辑}/Documents/development/c++/learncpp/helloworld/helloworld.cpp:6:10:错误:声明末尾应为“;” int x{ };^ ;生成 1 个错误。终端进程终止,退出代码:1 '''helloworld.cpp
4赞 Davis Herring 6/21/2020
显然没有被传递,并且您的编译器已经足够旧,可以默认为 C++03,其中该语法不起作用。-std=c++17

答:

0赞 rustyhu 6/21/2020 #1

参考列表初始化的解释,自 c++11 以来,此语法应该是合法的:

int main()
{
    int n0{};     // value-initialization (to zero)
    int n1{1};    // direct-list-initialization
    //...
}

我尝试在我的本地环境中编译您的代码,并且一切正常:

clang++ -std=c++17 -Wall -Weffc++ -Wextra -Wsign-conversion -Werror -pedantic-errors ...

clang++ --version
clang version 9.0.1 
Target: x86_64-pc-linux-gnu
Thread model: posix

也许您使用了一些类似的非 ASCII 的 ';' 字符?
我尝试使用汉字“;”代替并得到这个:

fly.cc:32:13: error: treating Unicode character <U+FF1B> as identifier character rather than as ';' symbol [-Werror,-Wunicode-homoglyph]
    int x{ }; 
            ^~
fly.cc:32:13: error: expected ';' at end of declaration
    int x{ }; 
            ^
            ;

评论

2赞 DevSolar 8/3/2022
那实际上不是一个汉字,只是一个全角的分号......
7赞 Greg Coleson 2/26/2021 #2

我遇到了同样的问题,我的tasks.json中出现了错误。这对我有用,试试看:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
      {
        "type": "shell",
        "label": "clang++ build active file",
        "command": "/usr/bin/clang++",
        "args": [
          "-std=c++17",
          "-stdlib=libc++",
          "-g",
          "${file}",
          "-o",
          "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
          "cwd": "${workspaceFolder}"
        },
        "problemMatcher": ["$gcc"],
        "group": {
          "kind": "build",
          "isDefault": true
        }
      }
    ]
  }

评论

0赞 Yar 7/13/2023
缺少的行可能是"-std=c++17",
0赞 starball 12/18/2023
@Yar,问题帖子中没有缺少这一行。
1赞 Romain Simon 8/3/2022 #3

我遇到了完全相同的问题,我尝试修改tasks.json,c_cpp_properties.json和settings.json,但没有任何效果。我终于尝试了此处显示的解决方案,即禁用 C/C++ Clang 命令适配器扩展,它对我有用!

0赞 Exchange_programming 8/15/2022 #4

我也被困在这个上一段时间了。这是让它为我工作的命令:

clang++ helloworld.cpp -o helloworld -std=c++17 && "<YOUR PATH TO THE FILE INSIDE THE QUOTES>"helloworld

例如"< YOUR PATH TO THE FILE INSIDE THE QUOTES >" = "/Users/< your username >/<something else>/"helloworld

我还安装了扩展程序,然后在设置中搜索,然后选中了显示.code runnerrun in terminalCode-runner: Run in terminal

您还应该能够在设置中搜索,然后设置默认的 Cpp 标准,但这对我不起作用,所以我不得不将其添加到命令中。C++