C++11提供了新的數據初始化的方法——直接初始化和拷貝列表初始化。
1.直接初始化:
int a{};//定義一個int型變量,初始化默認值爲0
int a{10};//定義一個int型變量,並初始化爲10
int a{1.1};//直接初始化不允許窄化(即:不允許{}內的內容精度高於定義類型)。{}內的內容爲1.1,精度高於int,存在窄化現象,編譯器會報錯
char s{"hello"};
int array1[]{ 1,2,3 };
char s1[ 3 ] { 'o', 'k' };
2.拷貝列表初始化
//拷貝列表初始化
/* Variable initialization */
int z = { 2 };
/* Array initialization */
int array2[] = { 4,5,6 };
char s2[] = { 'y','e','s' };
char s4[] = { "World" };
char s5[] = "Aloha"; // Omit curly braces (省略花括號)