? ? ? ? 前提引入:
? ? ? ? ? ? ? ? 1.類型名,在絕大多數(shù)編程時,我們都會引入類型來定義一個我們需要的數(shù)據(jù)。
? ? ? ? ? ? ? ? 類型眾多,偶爾我們會遇見一串類型名,使用起來無比復(fù)雜。存在拼寫錯誤,含義不明確導(dǎo)致出錯的問題。
? ? ? ? ? ? ? ? 列如:
std::map<std::string, std::string> m{ { "apple", "蘋果" }, { "orange", "橙子" }, {"pear","梨"} }; std::map<std::string, std::string>::iterator it = m.begin();
? ? ? ? ? ?在這串代碼中,std::map<std::string, std::string>::iterator 是一個類型,但是該類型太長了,特別容易寫錯。如何簡化呢。
? ? ? ? 在C中,typedef 作為一個可以取別名的一個關(guān)鍵字。確實可以省事許多,卻任然存在缺陷。
typedef std::map<std::string, std::string> Map;
? ? ? ? 若 typedef 為指針取了別名。存在小問題。
typedef char* pstring; int main() { const pstring p1; // 編譯成功還是失敗? const pstring* p2; // 編譯成功還是失?。? return 0; }
? ? ? ? C++是怎么做的呢,設(shè)計師為了不想寫復(fù)雜的類型,引入了auto關(guān)鍵字。
? ? ? ? auto :
? ? ? ?1.在早期C/C++中auto的含義是:使用auto修飾的變量,是具有自動存儲器的局部變量
? ? ? ?2.C++11中,標(biāo)準(zhǔn)委員會賦予了auto全新的含義即:auto不再是一個存儲類型指示符,而是作為一個新的類型指示符來指示編譯器,auto聲明的變量必須由編譯器在編譯時期推導(dǎo)而得
? ? ? ? 注:既然auto作為推導(dǎo)而得,在使用auto時,必須初始化。?文章來源地址http://www.zghlxwxcb.cn/news/detail-410099.html
?auto 的使用場景
? ? ? ? 1. auto 在推導(dǎo)指針是,不必再加*號;
? ? ? ? 2.auto在使用引用時,必須遵循規(guī)則加上&號;
? ? ? ? 3.不能作為函數(shù)的參數(shù)使用
? ? ? ? 4.不能直接用來聲明數(shù)組。
? ? ? ? 5.一行多個數(shù)據(jù)推導(dǎo)必須同類型。
? ? ? ??
????????
int main() { //1 int x = 10; auto a = &x; auto* b = &x; auto& c = x; cout << typeid(a).name() << endl; cout << typeid(b).name() << endl; cout << typeid(c).name() << endl; *a = 20; *b = 30; c = 40; //5 void TestAuto() { auto a = 1, b = 2; auto c = 3, d = 4.0; //錯 } return 0; }
?文章來源:http://www.zghlxwxcb.cn/news/detail-410099.html
?
到了這里,關(guān)于C++ : auto關(guān)鍵字的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!