auto 關鍵字在 C++ 中,auto 關鍵字是 C++11 引入的強大功能,用來宣告型別會被推導出來的變數。
編譯器會根據初始值推導出變數的型別,讓程式碼更好閱讀、也更好維護。
看看下面這個例子,auto 被用來宣告變數:
auto dragon_population{3}; // dragon_population is deduced as an integer
auto westeros{7.7777}; // westeros is deduced as a double
auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string
在每個例子裡,變數的型別都是從初始化時所用的值推導出來的。
auto 關鍵字省去了明確寫出型別的冗長,讓程式碼更精簡、也更好讀。
const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"};
auto purple_wedding_pie{pigeon_pie};
purple_wedding_pie.emplace_back("the strangler");
在這段程式碼中,auto 把 purple_wedding_pie 的型別推導為 std::vector<std::string>,省下了再明確寫一次型別的麻煩。
auto 關鍵字可以和 C++ 的各種語法結構搭配使用,是現代 C++ 程式設計中靈活好用的一項工具。
auto& element{array[0]}; // reference to an element
const auto object{otherObject}; // const type version of otherObject's type
auto* ptr{&x}; // pointer to x with the same type as x, but as a pointer.
在之後的單元裡,我們會經常看到 auto 關鍵字搭配 Lambda 表達式、範圍式 for 迴圈和迭代器。
auto 特別好用。auto 可以減少雜亂,提升程式碼的可維護性。