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出来的类型到底是什么,这样才能做到心中有数,出现问题才能快速定位。

转载于:https://www.cnblogs.com/cauchy007/p/4966361.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值