使用using与typedef来定义别名
使用using與typedef來(lái)定義別名
在C++中,using與typedef這兩個(gè)關(guān)鍵詞是大家用的比較多的,using關(guān)鍵詞用的最多的是using namespace的搭配如using namespace std;而typedef用來(lái)設(shè)為某個(gè)類(lèi)型設(shè)置一個(gè)別名,如typedef unsigned long long uint64;不過(guò),可能有些不知道,其實(shí)using也可以用來(lái)設(shè)置別名,在這種情況下,它與typedef所表述的意思沒(méi)有區(qū)別。使用using來(lái)設(shè)置一個(gè)別名方法如下:
using uint64 = unsigned long long;C++標(biāo)準(zhǔn)上描述為:
A typedef-name can also be introduced by analias-declaration. The identifier following the using keyword becomes atypedef-name and the optional attribute-specifier-seq following the identifierappertains to that typedef-name. It has the same semantics as if it wereintroduced by the typedef specifier. In particular, it does not define a newtype and it shall not appear in the type-id
?因此在普通的類(lèi)型名定義時(shí),理論上講二者是沒(méi)有區(qū)別的,當(dāng)然,我們知道,還有一種方式定義類(lèi)型別名,效果也是一樣的,那就是#define。
using與typedef在C++11標(biāo)準(zhǔn)以后對(duì)于模板類(lèi)型別名聲明有了一點(diǎn)區(qū)別。考慮到如下寫(xiě)法:
template <typename T> typedef std::vector<T> v;//使用typedeftemplate <typename T> using v = std::vector<T>;//使用using看起來(lái)好像是都可以的寫(xiě)法,但是使用typedef時(shí),編譯器會(huì)報(bào)錯(cuò)error: template declaration of ‘typedef’
也就是說(shuō),C++編譯器不支持使用typedef關(guān)鍵詞為模板類(lèi)設(shè)置別名,但是使用using的方式聲明一個(gè)關(guān)鍵詞卻是允許的,只是這個(gè)是C++11標(biāo)準(zhǔn)才有的,如果在編譯時(shí)不加上--std=c++11使用新的標(biāo)準(zhǔn)的話(huà),編譯器一樣會(huì)報(bào)錯(cuò)。
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的使用using与typedef来定义别名的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: string 类的初始化和赋值(程序成长
- 下一篇: c++ 运行时错误