如何在C++中使用auto关键字

How to use auto keyword in C++

本文关键字:auto 关键字 C++      更新时间:2023-10-16

我有一个类型为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;//错误:无法删除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。您能特别告诉我您得到的错误吗?

auto在C++中的意思是"为初始化表达式的类型设置变量类型",在您的情况下,无论"读取JSON"表达式返回什么。您无法将该类型输出到std::cout,因为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的事情,但我想现在这已经足够了。