• C++11新标准:auto关键字


    一、auto意义

      编程时常常需要把表达式的值赋给变量,这就要求在声明变量的时候清楚地知道表达式的类型,然后要做到这一点并非那么容易。为了解决这个问题,C++11新标准引入了auto类型说明符,用它就能让编译器替我们去分析表达式所属的类型。

    二、auto用法

      1.基本用法

        int tempA = 1;
        int tempB = 2;
        /*1.正常推断auto为int,编译通过*/
        auto autoTempA = tempA + tempB;
        /*2.正常推断auto为int,编译通过*/
        auto autoTempB = 1, *autoTempC = &autoTempB;
        /*3.autoTempD推断为int,autoTempE推断为double,编译不过*/
        auto autoTempD = 1, autoTempE = 3.14; 

      2.与const结合

        const int ctempA = 1;
        auto autoTempA = ctempA;
        
        /*1.cautoTempA推断为int,但是手动加了const,所以cautoTempA最终类型为const int*/
        const auto cautoTempA = ctempA;
        /*2.autoTempA推断为int,忽略顶层const*/
        autoTempA = 4;

      3.与引用结合

        int tempA = 1;
        int &refTempA = tempA;
        /*1.忽略引用,autoTempA推断为int,refAutoTempA被手动置为引用*/
        auto autoTempA = refTempA;
        auto &refAutoTempA = refTempA;
    
        autoTempA = 4;
        refAutoTempA = 3;
        /*2.输出为3,3,4,3*/
        cout<<"tempA     = "<<tempA<<endl;
        cout<<"refTempA  = "<<refTempA<<endl;
        cout<<"autoTempA = "<<autoTempA<<endl;
        cout<<"refAutoTempA = "<<refAutoTempA<<endl;

      4.与指针结合

       int tempA = 1;
        const int ctempA = 2;
    
        /*1.ptrTempA中auto推断为int*,ptrTempB中推断为int  */
        auto  ptrTempA = &tempA;
        auto *ptrTempB = &tempA;    
        /*2.cptrTempA中auto推断为const int*,cptrTempB中推断为cosnt int  */
        auto  cptrTempA = &ctempA;
        auto *cptrTempB = &ctempA;
        /*3.ptrTempA和ptrTempB输出完全一致*/
        cout<<" ptrTempA = "<<ptrTempA<<endl;
        cout<<"*ptrTempA = "<<*ptrTempA<<endl;
        cout<<" ptrTempB = "<<ptrTempB<<endl;
        cout<<"*ptrTempB = "<<*ptrTempB<<endl;
        /*4.cptrTempA和cptrTempB输出完全一致*/
        cout<<" cptrTempA = "<<cptrTempA<<endl;
        cout<<"*cptrTempA = "<<*cptrTempA<<endl;
        cout<<" cptrTempB = "<<cptrTempB<<endl;
        cout<<"*cptrTempB = "<<*cptrTempB<<endl;
        /*5.cptrTempA指向的为const int,不能通过cptrTempA来修改其值,编译不过*/
        *cptrTempA = 3;

    三、auto使用总结

      上面的例子只是为了说明auto与const、引用和指针的用法,在实际工作中,auto主要还是为了简化一些复杂的声明;但是建议在使用时必须要清楚自己auto出来的类型到底是什么,这样才能做到心中有数,出现问题才能快速定位。

  • 相关阅读:
    《把时间当作朋友》读书笔记
    Oracle&SQLServer中实现跨库查询
    Android学习——界面互调2
    《IT不再重要》读后感
    Android学习——数据存储
    Android学习——编写菜单
    Android学习——后台程序
    Android学习——写个小实例
    Android学习——界面编程!
    深入理解JavaScript系列(42):设计模式之原型模式
  • 原文地址:https://www.cnblogs.com/cauchy007/p/4966361.html
Copyright © 2020-2023  润新知