`a

`auto` 属于 C++

1 个练习

关于 `auto`

C++ 中的 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 能减少杂乱、提升代码的可维护性。
  • 基于迭代器的算法:它简化了算法中迭代器的使用,提升代码的可读性。
通过 GitHub 编辑 该链接会在新窗口或标签页中打开

学习 `auto`

练习已锁定

再解锁 1 个练习即可练习 `auto`