First, the meaning of auto
Programming often requires assigning the value of an expression to a variable, which requires a clear understanding of the type of the expression when declaring the variable, and then it is not easy to do so. To solve this problem, the c++11 new standard introduces the auto type specifier, which allows the compiler to parse the type that the expression belongs to.
Second, auto usage
1. Basic usage
intTempa =1; intTEMPB =2; /*1. Normal inference auto is int, compile through*/Auto Autotempa= Tempa +TEMPB; /*2. Normal inference auto is int, compile through*/Auto AUTOTEMPB=1, *AUTOTEMPC = &AUTOTEMPB; /*3.autoTempD Inference is Int,autotempe inferred as double, but the compilation*/Auto AUTOTEMPD=1, Autotempe =3.14;
2. Combining with Const
Const int 1 ; = Ctempa; /* 1.cautoTempA is inferred as int, but is manually added const, so the Cautotempa end type is const int */ Const Auto Cautotempa = Ctempa; /* 2.autoTempA inferred to be int, ignoring top-level const */ 4;
3. Combining with references
intTempa =1; int&reftempa =Tempa; /*1. Ignore references, Autotempa inference to Int,refautotempa is manually set as reference*/Auto Autotempa=Reftempa; Auto&refautotempa =Reftempa; Autotempa=4; Refautotempa=3; /*2. Output is 3,3,4,3*/cout<<"Tempa ="<<tempA<<Endl; cout<<"Reftempa ="<<refTempA<<Endl; cout<<"Autotempa ="<<autoTempA<<Endl; cout<<"Refautotempa ="<<refAutoTempA<<endl;
4. Binding with the pointer
intTempa =1; Const intCtempa =2; /*1.ptrTempA in auto inference to INT*,PTRTEMPB as int*/Auto Ptrtempa= &Tempa; Auto*PTRTEMPB = &Tempa; /*2.cptrTempA in auto inference to const INT*,CPTRTEMPB inferred as cosnt int*/Auto Cptrtempa= &Ctempa; Auto*CPTRTEMPB = &Ctempa; /*3.ptrTempA and PTRTEMPB outputs are fully consistent*/cout<<"Ptrtempa ="<<ptrTempA<<Endl; cout<<"*ptrtempa ="<<*ptrTempA<<Endl; cout<<"PTRTEMPB ="<<ptrTempB<<Endl; cout<<"*PTRTEMPB ="<<*ptrTempB<<Endl; /*4.cptrTempA and CPTRTEMPB outputs are fully consistent*/cout<<"Cptrtempa ="<<cptrTempA<<Endl; cout<<"*cptrtempa ="<<*cptrTempA<<Endl; cout<<"CPTRTEMPB ="<<cptrTempB<<Endl; cout<<"*CPTRTEMPB ="<<*cptrTempB<<Endl; /*the 5.cptrTempA points to a const int, which cannot be modified by Cptrtempa, but is compiled*/*cptrtempa =3;
Iii. Summary of the use of auto
The above example is only to illustrate the use of auto and const, reference and pointers, in the actual work, auto is mainly to simplify some complex statements, but it is recommended to use it must be clear what the type of auto come out, so as to be aware of problems in order to quickly locate.
C++11 new standard: auto keyword