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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/224515

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午12:28
下一篇 2023年2月13日 下午12:28

相关推荐