c++神奇的寫法(一)
阿新 • • 發佈:2019-02-12
最近看《c++primer》一書,除了學到很多基礎知識,還學到很多很神奇的寫法,接下來就來總結一下,感覺就像黑魔法一樣,雖然應該很少機會會用到:)
變數和基本型別
auto型別說明符
- 作用:能讓編譯器替我們去分析表示式的型別
- 注意點:
- auto定義的變數必須有初始值
- 使用auto也能在一條語句中宣告多個變數,但是他們的型別必須相同
- auto未必會推斷出正確的型別
- 當引用被作為初始值時,編譯器會以引用所指的型別作為auto的型別
- auto一般會忽略頂層const,但會保留底層const
- 如果希望保留引用或頂層const的話,要明確指出來
int a = 1 ,&b = a;
const int c = 1,&d = c;
auto x_1 = a; //x_1 is int
auto x_2 = b; //x_2 is int
auto x_3 = c; //x_3 is int
auto x_4 = d; //x_4 is int
auto x_5 = &a; //x_5 is a pointer to int
auto x_6 = &c; //x_6 is a pointer to const int
const auto x_7 = d; //x_7 is const int
auto &x_8=c; //x_8 is a reference to const int
const auto &x_9=32; //x_9 is a reference to const int
(c++11標準)
decltype型別指示符
- 作用:希望從表示式推斷出要定義的型別,但不用表示式的值初始化變數
- 注意點:
- 不會忽略頂層const和引用
- 有些表示式會給decltype一個引用的型別
- decltype((variable))的結果永遠是引用,decltype(variable)的結果只有當variable是一個引用時才是引用,因為(variable)會看成是一個表示式
*當我們對某個函式用decltype時,得到的是function type,而不是a pointer to function
字串、向量和陣列
標準庫函式begin()和end()
- 作用:返回指向首指標和尾後指標
- 注意點:定義在iterator標頭檔案
使用陣列初始化vector物件
- 步驟:
int int_arr[ ]={0,1,2,3,4,5};
vector<int> ivec(begin(int_arr),end(int_arr));
- 注意點:不允許使用一個數組初始化另外一個數組,也不允許使用vector物件初始化陣列,但是可以用陣列來初始化vector物件
用new動態分配記憶體
- default initialized(會導致built-in-type物件有undefined值)
int *pi = new int; // pi指向uninitialized int
string *ps = new string; // ps指向空string
- direct initialized(和copy initialized相對的那個)
int *pi = new int(1024);
string *ps = new string(10,'9');
- list initialized
vector<int> *pv = new vector<int>{0,1,2,3,4,5};
- value initialized
string *ps = new string(); // ps指向空string
int *pi = new int(); // pi指向0
- auto initialized
auto p1 = new auto(obj);