Several initialization methods of integer in C++11
0X00 Foreword
We all know that in C++, the most common integer initialization method is = assignment. But in fact, C++11 provides several ways.
There are more ways and more ways out. This is also for the convenience of developers. Don't say much, just start talking.
0X10 initialize with'='
This is the most common and commonly used method, and it is also an initialization method that fits daily habits. as follows:
int x=1;
Here, use'=' to assign x to 1.
0X11 Initialize with'()'
It is not so common to use (), and the value in parentheses is the initialized value. as follows:
int y(2);
The value of y is initialized to 2. The parentheses look simple and concise. And it looks a bit like a function, otherwise, if you get used to it, the overall code will look much more beautiful
0X12 Initialize with'{}'
Compared with the previous two, using'{}' is obviously not so beautiful and concise. as follows:
int z={
3};
Or remove the'=' and use'{}' directly
int z{
3};
Since it seems so complicated, why use it? In fact, we can think about whether this method is similar to the initialization of integer data, yes
int arry[2]={
1,2};
So such assignments are corroborated, and won’t appear so abrupt.
0X20 test
#include<iostream>
using namespace std;
int main()
{
int x=1;
int y(2);
int z{
3};
cout<<"用=初始化x为:"<<x<<endl;
cout<<"用()初始化y为:"<<y<<endl;
cout<<"用{}初始化z为:"<<z<<endl;
return 0;
}
Test Results: