文章

C++的auto关键字

自动类型推导。auto关键字可自动推导数据类型。

C++的auto关键字

auto关键字

auto会根据初始化表达式来推导变量的类型,因此变量必须在定义时初始化。

C++是强类型编程语言,使用auto会使C++类似于弱类型语言,不需要明确定义数据的类型(int、std::string等)。

auto的常见应用场景

  • for循环和迭代器,遍历可迭代对象。
  • 类型过于复杂(模板嵌套),而不得不用auto。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

int main()
{
    int array[] = { 1, 2, 3, 4, 5 };

    bool flag = true;
    for (auto& e : array)  // 示例1
    {
        if(!flag)
            std::cout << " ";
        std::cout << e;
        flag = false;
    }
    std::cout << "\n";

    std::vector<char> ch={'a', 'b', 'c', '\n'};
    for (auto it= ch.begin(); it!=ch.end(); it++)  // 示例2
    {
        std::cout << *it << " ";
    }
    return 0;
}

auto不能推导的场景

不初始化无法推导

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    auto a = 3;
    //auto b; // 错误。定义时必须初始化
    return 0;
}

auto不能作为函数的参数

auto作为函数的参数是C++20的新特性。C++20之前的标准不支持。

1
void func(auto v) {}

auto不能直接用来声明数组

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    int a[] = {1,2,3};
    // auto b[] = {4, 5, 6};  // 错误。'auto' type cannot appear in top-level array type
    return 0;
}
本文由作者按照 CC BY 4.0 进行授权