使用大括号在 C++ 中初始化变量时出现意外结果

Unexpected result when initializing variable in C++ using curly braces

我正在使用 atom 练习 C++(我是新手)。我刚学会像下面这样初始化变量:

#include <iostream>

using namespace std;

int main() {

  int myInt {};
  
  return 0;
}

当我在 codelite 中构建和 运行 之前的代码时,我没有收到任何错误。但是,如果我使用我的 MacBook 终端 (zsh) 编译我的 atom 文件 dailyPractice10.cpp,我会收到以下错误:

dailyPractice10.cpp:7:12: error: expected ';' at end of declaration
int myInt {};
        ^
        ;
1 error generated.

我正在使用以下命令在终端上编译它:

g++ -o dailyPractice10 dailyPractice10.cpp(编译)

./dailyPractice10 (运行s 程序)

有没有人反馈为什么这段代码在 codelite 中 运行 但不能在终端中编译?

因为这个特性是从c++11开始添加的。

如果您想尝试以下 command.it 就可以了。

$ g++ -std=c++0x -o dailyPractice10 dailyPractice10.cpp

解决此问题的关键是在构建代码时设置 C++11(或更高版本)标准。 在 IDE 的控制台选项卡中,在错误之前生成以下输出。请注意,在构建代码时没有定义标准:

make all 
Building file: ../1.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"1.d" -MT"1.o" -o "1.o" "../1.cpp"

我们需要在 g++ 命令中添加 --std=c++1x 标志。以下解决方案适用于使用 Eclipse IDE 和 MacOSX C++ 编译器的用户:

  1. 在“项目资源管理器”中右键单击项目。
  2. 转到属性 > C/C++ 构建 > 设置。
  3. 在“工具设置”选项卡下,找到“GCC C++ 编译器”>“杂项”

在“其他标志”文本框中,编辑文本,使其看起来像:

-std=c++17 -c -fmessage-length=0

如果您打算使用任何其他 c++ 标准,请将“c++17”替换为您选择的标准(例如 c++20)。

应用更改。 运行 清理,然后再次构建。