1.auto
型別推斷
a.引入原因
程式設計時,經常需要將表示式的值賦給變數,這就要求我們在申明變數的時候,明確知道表示式的型別,然而要做到這一點並不容易,於是引入auto讓編譯器幫我們去做型別分析。
b.使用注意事項
const
int const_i =1,
&const_ref = const_i;
auto b = const_i;
// b的型別是int,const_i的頂層屬性被忽略掉了。
const
auto b = const_i;
//b的型別是const int
auto c = const_ref;
//c是int, 等效auto c = const_i;
2.decltype
型別指示符
a.引入原因
有時候我們想用表示式的型別推斷要定義的變數的型別,但是我們不想用表示式的型別作為變數的初始值。
decltype(f
()) sum = x;
//sum的型別是f()的型別,初始值是x
b.使用注意事項const
int ci =0,
&cj = ci;
decltype
(ci) x =0;
//x的型別為const int
decltype
(cj) y = x;
//y的型別為const int&
decltype
(cj) z;
//錯誤,引用必須初始化
note:引用重來都是作為其所指物件的同義詞出現,只有在decltype
處是個例外。
int i =0,
*p =
&i;decltype
(*p) c = i;
//c的型別是int&
int i =0;
decltype
((i)
) d;
//錯誤d的型別是int&, 必須初始化
C 11 auto自動型別推導
1.auto型別推導auto x 5 正確,x是int型別 auto pi new auto 1 正確,批是int const auto v x,u 6 正確,v是const int 型別,u是const int static auto y 0.0 正確,y是double型別 auto int r ...
c 11 auto 型別說明符詳解
當使用 auto 自動推斷型別時,需要注意以下幾點 一 必須要有初始值 乙個顯而易見的道理,auto 表示編譯器根據初始值型別推斷宣告變數的型別,因此必須要有初始值。二 一條宣告語句只能有一種基本型別 auto i 0,p i 正確,基本型別是int auto sz 0,pi 3.14 錯誤,由sz...
C 11 auto和decltype關鍵字
可以用 auto 關鍵字定義變數,編譯器會自動判斷變數的型別。例如 auto i 100 i 是 int auto p new a p 是 a auto k 34343ll k 是 long long有時,變數的型別名特別長,使用 auto 就會很方便。例如 map mp for auto i mp...