1、C++11 auto关键字及用法

1.auto的功能:

auto 可以自动推理数据类型。

 使用语法如下:

#include<iostream>
#include<typeinfo>
using namespace std;

int main()
{
    //auto变量定义时必须初始化
    auto x = 3;
    auto y{23};
    //auto c;

    //定义一个auto的系列的变量必须始终推倒成同一类型
    auto x1{1}, x2{2};
    //auto a{10}, b{2.0};

    //如果初始化表达式是引用或const,则去除引用或const语义
    int& q{x1};
    auto m {q};
    cout<<"type of m: "<< typeid(m).name() <<endl;   //int
    m = 400;
    cout<< "q : " << q << " m : " << m <<endl;
    const int n{100};
    auto t {n};                       
    cout<<"type of t: "<< typeid(t).name() <<endl;   //int
    t = 300;
    cout<<"t : "<< t <<endl;  

    //如果auto关键字加上&,则不去除引用或const语意
    char ch1{'c'}, &ch2{ch1};
    auto& ch3{ch2};
    cout<<"type of ch3: "<< typeid(ch3).name() <<endl;   //char&
    ch3 = 'b';
    cout<<"ch1 : "<<ch1<<"  ch2 : "<<ch2<<"  ch3: "<<ch3<<endl;

    const double h {1.0};
    auto& k {h};
    cout<< "type of k: "<<typeid(k).name() <<endl; //const double
    //k = 12.0;

    //如果初始化为数组,auto自动推倒为指针
    int arr[3]{1,2,3};
    auto p {arr};
    cout<<"type of p: "<<typeid(p).name()<<endl; //int*
    cout<<"size of arr: "<<sizeof(arr)<<endl;
    cout<<"size of p: "<<sizeof(p)<<endl;

    //如果加上&,则推导为数组
    auto& px{arr};
    cout<<"type of px: "<<typeid(px).name()<<endl; //A3_i
    cout<<"size of px: "<<sizeof(px)<<endl;

    //C++14可以用auto来推倒函数返回值

    return 0;
}

注:auto不能用来定义数组或函数形参。

2.使用场景:

第一种经典场景:当变量的数据类型很复杂或者写起来很麻烦,我们懒得打字了,其实是为了加快编程效率。

list<string> c;
list<string>::iterator ite;
ite = find(c.begin(), c.end(), target);

//代替为下面
list<string> c;
auto ite = find(c.begin(), c.end(), target);

第二种经典场景: 当我们有时不确定函数返回值类型时, 或者说用auto来推理函数返回值类型。

template<typename T>
auto func(T a, T b){
   
   return max(a,b);
}
int main()
{
   cout << func(100,200) <<endl;
   cout << func(300.88, 400.55) <<endl;
   cout << func('a', 'A') << endl;

   return 0;
}

 3、不能使用auto的场景

  (1)不能作为函数参数使用。因为只有在函数调用的时候才会给函数参数传递实参,auto 要求必须要给修饰的变量赋值,因此二者矛盾。

int func(auto a, auto b)    // error
{    
    cout << "a: " << a <<", b: " << b << endl;
}

  (2)不能用于类的非静态成员变量的初始化

class Test
{
    auto v1 = 0;                    // error
    static auto v2 = 0;             // error,类的静态非常量成员不允许在类内部直接初始化
    static const auto v3 = 10;      // ok
}

  (3)不能使用 auto 关键字定义数组

int func()
{
    int array[] = {1,2,3,4,5};  // 定义数组
    auto t1 = array;            // ok, t1被推导为 int* 类型
    auto t2[] = array;          // error, auto无法定义数组
    auto t3[] = {1,2,3,4,5};;   // error, auto无法定义数组
}

  (4)无法使用 auto 推导出模板参数

template <typename T>
struct Test{}

int func()
{
    Test<double> t;
    Test<auto> t1 = t;           // error, 无法推导出模板类型
    return 0;
}

 

posted @ 2020-10-09 22:00  zwj鹿港小镇  阅读(627)  评论(0编辑  收藏  举报