我理解int x{};
是一种默认初始化,但它是否与int x = 0;
完全相同?
有所不同:
int x=1.888;
这样的写法会让x变成1,但是以后可能会出现很多麻烦。所有专业人士都曾经在自己或他人的代码中遇到过这种情况。
但是,int x{1.888};
这样的写法则无法编译通过,可以避免这种麻烦。
int x{}
将像 static int x
一样初始化 x
;即为零。话虽如此,我认为int x = 0
更清晰,并且它有一个好处,就是可以适用于旧的C++标准。0
。#include <iostream>
#include <string>
using namespace std;
int main()
{
int y{};
int x = 0;
cout << "y: " << y << endl;
cout << "x: " << x << endl;
return 0;
}
输出:
y: 0
x: 0