• 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;
    }
    111
  • 相关阅读:
    Springboot 连接数据库
    线程专题 -- 线程的创建,状态,工作过程,常见方法
    MySQL中UPDATE语句里SET后使用AND的执行过程和结果分析
    SpringCloud | 通过电商业务场景让你彻底明白SpringCloud核心组件的底层原理
    避坑 | Java8使用并行流(ParallelStream)注意事项
    Spring--AOP、通知的执行顺序
    JVM--理解介绍
    JSF学习实战
    策略模式--实战1
    二叉树、二叉查找树、平衡树和红黑树概念
  • 原文地址:https://www.cnblogs.com/zwj-199306231519/p/13789085.html
Copyright © 2020-2023  润新知