简体   繁体   English

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

[英]Unexpected result when initializing variable in C++ using curly braces

I'm using atom to practice C++ (I'm very new).我正在使用 atom 练习 C++ (我很新)。 I just learned to initialize variables like the following:我刚刚学会了初始化变量,如下所示:

#include <iostream>

using namespace std;

int main() {

  int myInt {};
  
  return 0;
}

When I build and run the previous code in codelite I receive no errors.当我在 codelite 中构建和运行以前的代码时,我没有收到任何错误。 However, if I compile my atom file dailyPractice10.cpp using my MacBook terminal (zsh) I get the following error:但是,如果我使用我的 MacBook 终端 (zsh) 编译我的 atom 文件 dailyPractice10.cpp,我会收到以下错误:

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

I'm using the following command to compile it on terminal:我正在使用以下命令在终端上编译它:

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

./dailyPractice10 (runs program) ./dailyPractice10(运行程序)

Does anyone have any feedback why this code runs in codelite but doesn't compile in terminal?有没有人有任何反馈,为什么这段代码在 codelite 中运行但不在终端中编译?

Because this feature is added from c++11.因为这个特性是从 c++11 添加的。

if you will like to try below command.it will work.如果您想尝试以下命令。它将起作用。

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

The key to fixing this issue is to set the C++11 (or above) standards while building your code.解决此问题的关键是在构建代码时设置 C++11(或更高版本)标准。 In the console tab of the IDE, the following output is generated before the error.在IDE的console选项卡中,报错前生成如下output。 Notice that no standard is being defined while building the code:请注意,在构建代码时没有定义标准:

 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"

We need to add the --std=c++1x flag to the g++ command.我们需要在 g++ 命令中添加--std=c++1x标志。 The following solution is for the ones using the Eclipse IDE and the MacOSX C++ compiler:以下解决方案适用于使用 Eclipse IDE 和 MacOSX C++ 编译器的解决方案:

  1. Right click on the project from the "Project Explorer".右键单击“项目资源管理器”中的项目。
  2. Go to Properties > C/C++ Build > Settings. Go 到属性 > C/C++ 构建 > 设置。
  3. Under the "Tool Settings" tab, find "GCC C++ Compiler" > "Miscellaneous"在“工具设置”选项卡下,找到“GCC C++ 编译器”>“杂项”

In the "Other Flags" text box, edit the text such that it looks like:在“其他标志”文本框中,编辑文本,使其如下所示:

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

If you intend to use any other c++ standard, replace "c++17" with the standard of your choice ( eg. c++20).如果您打算使用任何其他 c++ 标准,请将“c++17”替换为您选择的标准(例如 c++20)。

Apply Changes.应用更改。 Run Clean, and the Build again.运行 Clean,然后再次构建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM