C++11標準——初始化

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 (省略花括號)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章