c++编译错误'预期';'使用直接大括号初始化时在声明结尾处

问题描述 投票:0回答:5

我对 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{ };
无法正常工作来初始化变量以及我可以做些什么来修复它以便它可以工作吗?

[编辑]:我检查/测试的更多设置:

  • 使用
    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++ visual-studio-code compiler-errors c++17
5个回答
7
投票

我遇到了同样的问题,并且我的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
        }
      }
    ]
  }

1
投票

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


0
投票

参考List初始化的解释,这个语法从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{ }; 
            ^
            ;

0
投票

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

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 runner
,然后在设置中搜索
run in terminal
,然后选中了
Code-runner: Run in terminal
的框。

您还应该能够在设置中搜索

C++
,然后设置默认的 Cpp 标准,但这对我来说从来没有用,所以我必须将其添加到命令中。


0
投票

对于那些遇到 Code Runner 问题的人,问题是我们没有指定 Code Runner 使用哪个版本,为此,请转到

extensions > code runner > extension configuration > edit
中已安装的
settings.json
查看 code-runer.executorMap:

在我的例子中,cpp 所在的行位于代码 21 行。在

$filename
之后,你将
-std=c++17

// It should look similar to this
"cpp": "cd $dir && g++ $fileName -std=c++17 -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

它对我有用并解决了这个问题,c ++ 17取决于编译器的版本

© www.soinside.com 2019 - 2024. All rights reserved.