我已经阅读了很多 C++ 代码,并且遇到了两种初始化变量的方法。
方法一:
int score = 0;
方法二:
int score {};
我知道 int score {};
会将分数初始化为 0,所以 int score = 0;
这两者有什么区别?我读过initialization: parenthesis vs. equals sign但这并没有回答我的问题。我想知道等号 和花括号 之间有什么区别,而不是圆括号。在什么情况下应该使用哪一个?
最佳答案
int score = 0;
执行 copy initialization ,作为效果,score
被初始化为指定值0
。
Otherwise (if neither
T
nor the type ofother
are class types), standard conversions are used, if necessary, to convert the value ofother
to the cv-unqualified version ofT
.
int score {};
执行 value initialization带有自 C++11 起支持的大括号初始化器作为效果,
otherwise, the object is zero-initialized.
score
是内置类型int
,它是zero-initialized最后,即初始化为 0
。
If
T
is a scalar type, the object's initial value is the integral constant zero explicitly converted toT
.
关于c++ - 在 C++ 中初始化变量的 = 和 {} 语法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405190/