Prior to c++11, the type of initialization was not always uniform.
For example the following two man definitions, one as a struct, one as a class. The initialization of the two is not the same.
#include <iostream>using namespace std;struct manstruct{string name;int age;}; Class manclass{private:string Name;int Age;public:manclass (String s,int a): name (s), age (a) {}};int main () {manstruct ms= {"struct", 10};manclass MC ("Class", 99);}
For structs, you can use {...} syntax, but for a class version, if you use the
Manclass mc={"Class", 88};
Compilation Result:
But c++11 is allowed to use {...} The type of syntax initialization.
Compile-time using the C++11 feature, the compilation can pass smoothly.
Even the equals sign can be ignored.
For example:
#include <iostream>using namespace std;struct manstruct{string name;int age;}; Class manclass{private:string Name;int Age;public:manclass (String s,int a): name (s), age (a) {}};int main () {manstruct ms= {"struct", 10};manclass mc={"class", 88};manclass mc2{"class", 999};}
The same can be successfully compiled through
The use of unified initialization also prevents narrowing . Because C + + can implicitly perform narrowing.
For example:
#include <iostream>using namespace std;void func (const int i) {cout<< "i=" <<I<<ENDL;} int main () {func (10.555);}
Execution Result:
You can see that 10.555 is narrowed to 10, but using unified initialization avoids this situation
Found me here just came out with a warning only. Or it can be narrowed.
Unified initialization can also be used to initialize dynamically allocated arrays .
For example:
#include <iostream>using namespace Std;int main () {int *ar=new int[5]{1,2,3,4,5};cout<< "ar:"; for (int i=0;i <5;i++) cout<<ar[i]<< ""; Cout<<endl;}
Run:
Unified initialization can also initialize a class member array in the constructor initializer .
#include <iostream>using namespace Std;class man{private:int ar[4];p ublic:man (): Ar{1,2,3,4}{}void showAr () const{for (int i=0;i<4;i++) cout<<ar[i]<<endl;}}; int main () {man M;m.showar ();}
Run: