【C++】C++中typedef、auto與decltype的做用

typedef

類型別名(type alias)是一個名字,使用typedef不會真正地建立一種新的數據類型,它只是已經存在數據類型的一個新名稱。
語法:ios

typedef type name;

其中type是c++中的數據類型,name是這個類型的一個別名。

C++11提供了引用的功能,關於引用的詳細介紹能夠參考筆者以前的文章。引用爲變量提供別名,typedef則是爲類型提供別名。

例如:c++

#include <iostream>
int main(){
    int m = 10;//使用int定義變量m
    typedef int integer;//建立一個int的別名爲integer
    integer n = 20;//使用integer定義變量n
    typedef integer integer_type;//建立一個integer的別名爲integer_type
    integer_type o = 30;//使用integer_type定義變量o
    std::cout << "m + n + o = " << (m+n+o) << std::endl;//運算
    return 0;
}

輸出結果:spa

m + n + o = 60

上面有兩個別名integer和integer_type,integer_type有integer建立而來,integer_type和integer都是屬於int類型。指針

c++11還爲提供別名提供了另外一種更爲簡便的方法—別名聲明(alias declaration),例如:c++11

using integer = int; // integer是int的同義詞

這種方法的規則是用using關鍵字做爲別名的開始,其後緊跟別名和等號。code

 

auto

auto是c++11標準定義的一個類型推斷的關鍵字,auto可以讓編譯器自動去分析表達式所屬的類型,與特定的數據類型不一樣(好比double),讓編譯器經過初始值來推算變量的類型。顯然auto定義必須有初始值。
好比:blog

#include <iostream>
#include <typeinfo>
#include <set>
using namespace std;

int main()
{
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << "x type is : " << typeid(x).name() << endl
 << "y type is : " << typeid(y).name() << endl
 << "ptr type is : " << typeid(ptr).name() << endl;

cout << "--------------------------" << endl;

set<string> strs;
strs.insert({"green","blue","red"});
for(auto it = strs.begin();it != str.end();it++){//遍歷容器中的元素
    cout << *it << " ";
}

cout << "--------------------------" << endl;

//r是一個int引用類型
auto &r = x;
cout << "r type is : " << typeid(r).name() << endl;

return 0;
}

輸出結果:編譯器

x type is : i
y type is : d
ptr type is : Pi
--------------------------
blue green red
--------------------------
r type is : i

上面的i表示int,d表示double,Pi表示int*(int類型的指針)。string

decltype

decltype也是c++11提供的一個關鍵字,它能夠從變量或表達式中提取類型。it

int f() { return 10; }
int main(){
    decltype(f()) val;//f()返回值是int類型,val是int類型

    const int &v = 10;
    decltype(v) rval;//錯誤,rval 是引用類型,必需要初始化

    int pv = 10;
    int *p = &pv;
    decltype(p) pp;//正確,pp是int*類型。
    decltype(*p) c;//錯誤,c是int&類型(int引用類型),必需要初始化
    return 0;
}

若是表達式是解引用操做(*),那麼decltype將會獲得引用類型。如上面的decltype(*p)。

若是decltype裏面有兩個括號,那麼是一個引用類型

decltype((i)) d;//錯誤,d是int&,必需要初始化。
decltype(i) e;//正確,e是一個(未初始化)int。

 

注意:

decltype((variable))(注意是雙括號)的結果永遠是引用,而decltype(variable)結果只有當variable自己是引用時纔是引用。

相關文章
相關標籤/搜索