简体   繁体   English

在 C++ 中初始化变量的 = 和 {} 语法之间的区别

[英]Difference between = and {} syntaxes for initializing a variable in C++

I have read quite a few C++ codes, and I have come across two methods of initialising a variable.我已经阅读了很多 C++ 代码,并且遇到了两种初始化变量的方法。

Method 1:方法一:

int score = 0;

Method 2:方法二:

int score {};

I know that int score {};我知道int score {}; will initialise the score to 0, and so will int score = 0;将分数初始化为 0,因此int score = 0;

What is the difference between these two?这两者有什么区别? I have read initialization: parenthesis vs. equals sign but that does not answer my question.我已经阅读了初始化:括号与等号,但这并没有回答我的问题。 I wish to know what is the difference between equal sign and curly brackets , not parenthesis.我想知道等号大括号之间有什么区别,而不是括号。 Which one should be used in which case?在什么情况下应该使用哪一个?

int score = 0; performs copy initialization , as the effect, score is initialized to the specified value 0 .执行 复制初始化,作为效果, score被初始化为指定值0

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T .否则(如果Tother的类型都不是类类型),如有必要,将使用标准转换other的值转换为T的 cv 非限定版本。

int score {}; performsvalue initialization with braced initializer, which was supported since C++11, as the effect,使用从 C++11 开始支持的花括号初始化器执行值初始化,作为效果,

otherwise, the object is zero-initialized .否则,对象是 零初始化的

score is of built-in type int , it's zero-initialized at last, ie initialized to 0 . score是内置类型int ,它最后 被初始化为零,即初始化为0

If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T .如果T是标量类型,则对象的初始值是显式转换T的整数常量零。

You may have some interest in ISO/IEC 14882 8.5.1.您可能对 ISO/IEC 14882 8.5.1 感兴趣。 It will tell you that a brace-or-equal-initializer can be assignment-expression or braced-init-list .它会告诉你一个大括号或等号初始化器可以是assignment-expressionbraced-init-list In Method2, you are using an default initializer on a scalar type, witch should be set to zero.在 Method2 中,您在标量类型上使用默认初始值设定项,应将 witch 设置为零。

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

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