簡體   English   中英

如何在 C++ 中使用 auto 關鍵字

[英]How to use auto keyword in C++

我有類型為auto C++ 代碼:

auto T = reads a JSON

我需要使用打印T的內容

cout << T << endl;

它不工作。 你能幫助我嗎?

在 C++11 中,您可以使用 auto.1 聲明變量或對象,而無需指定其特定類型。例如:

   auto i = 42; // i has type int 
    double f(); 
    auto d = f(); // d has type double 

用 auto 聲明的變量的類型是從它的初始值設定項中推導出來的。 因此,需要進行初始化:

自動我; // 錯誤:無法推斷 i 的類型

允許額外的限定符。 例如:

靜態自動增值稅 = 0.19;

當類型很長和/或很復雜的表達式時,使用 auto 尤其有用。 例如:

vector<string> v; ... auto pos = v.begin(); // pos has type        vector<string>::iterator
auto l = [] (int x) -> bool { // l has the type of a lambda ..., // taking an int and returning a bool };

簡而言之, auto 可以推斷出任何類型。您的程序無法正常工作,因為它可能無法解析 JSON 或編譯器很舊(其中不支持 auto 。您能具體告訴我您遇到的錯誤嗎?

C++ 中的auto表示“為初始化表達式類型設置變量類型”,在您的情況下,無論“讀取 JSON”表達式返回什么。 您無法將該類型輸出到std::cout因為沒有為此類類型定義operator<< ,可能有許多可能的原因,因為未提供 operator,您假設使用其他東西,缺少標頭等。解決方案將取決於實際類型。

好的 ! 在告訴您如何使用auto ,我必須告訴您它是C++11的最佳特性之一,並且通過以下方式使C++更加高效:-

  1. 減少代碼量

  2. 強制初始化

  3. 增加通用性(在 C++17 中)

首先auto只有一份工作。 它將通過傳遞給對象的值來推斷對象的類型。 例如:-

auto x = 5;

這意味着x是一個值為 5 的整數。每當您使用auto您必須初始化該變量(這是一件好事),並且您不能在語句中對多種類型使用 auto。 例如:-

auto x;  // illegal ! x isn't initialized so compiler cannot dduce it's type
auto z=5, y=7;  // legal because z & y are both integers
auto a=8, ch= 'c';  // illegal ! an integer & a character in a single statement, hence type deduction ambiguity

auto的精華不在於初始化intchar等數據類型。 它對於像iterators這樣的classes更方便。 例如:-

vector<int> v;
vector<int>::iterator i1 = v.begin();
auto i2 = v.begin();   // see how auto reduces the code length

這在for循環中更為明顯:-

for (vector<int>::iterator i = v.begin(); i!=v.end(); ++i);

可以減少到:-

for (auto i = v.begin(), i!=v.end(); ++i);

如果您對上述內容不滿意,那么這可能會激發您使用auto :-

vector< map <int, vector<string> > >::iterator i1 = v.begin();  // where v is the vector of maps of ints & vectors of strings !!!!
auto i2 = v.begin();

我所說的通用性是通過auto將值傳遞給函數。 喜歡 :-

void add (auto x, auto y)
{
    cout << x+y << '\n';
}

這在當前標准中是不可能的,並且已針對 C++17 提出。 這可能會在不使用templates情況下增加函數的通用能力。 但是,此語法適用於lambda functions :-

auto l = [](auto x, auto y) { return x+y; }   // legal from C++14 onwards

但是,在 lambda 中使用大括號時要小心,因為您可能認為:-

auto x = {5};

是一個整數,但它實際上是一個intializer_list<int>類型的對象。 我可以解釋很多關於auto的地獄,但我想現在這已經足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM