C++11中对关键字auto进行了重新定义,可以让编译器根据初始值类型自动推断变量的类型。
1 2 3 |
auto a? = 0;? ?//推断出a类型为int atuo b = 0.0; ?//推断出b类型doublu auto c = 'A'; ?//推断出c类型是char |
如果不知道为什么能自动推断出来可以看下:常量类型? ? ?和? ?C++常量类型?获取
上面写的都是推断基本类型,当然C++11 auto关键字并非这样简单的运用,更多的是为了自定义类型推断。相信很多人在写迭代器时会很头痛,太长了。先写个vector<double>类型的迭代器。
1 2 |
std::vector<double> sc; std::vector<double>::iterator iter = sc.begin(); |
可能还有人会说,可以用typedef重新定义别名,这样是可以解决太长的问题,但这样代码又多出了一行。
1 2 3 4 5 |
typedef std::vector<double>::iterator IterVecDouble; std::vector<double> sc; IterVecDouble iter = sc.begin(); |
接下来用C++11 auto关键字写一下以上代码,大家可以比对看看,哪个更洁简。
1 2 |
std::vector<double> sc; auto iter = sc.begin(); |
上面三段代码中可以看出用auto关键字,代码最洁简。这才是auto自动推断类型的好处,可以让代码洁简,更重要的是不用当心类型不匹配问题。
使用C++11 auto关键字也有几点要注意的地方。
1、使用auto关键字的变量必须有初始值。
这个很好理解,没有初始值,编译器就无法推断出变量类型。
1 2 |
auto a;? ?//推断不出a类型 错误Error atuo b = 0.0; ?//推断出b类型doublu |
2.使用auto关键字声明变量的类型,不能自动推导出顶层的CV-qualifiers和引用类型,除非显示声明。
1 2 3 4 5 6 7 8 9 10 |
int i = 10; int &r = i; auto a = r; //此处a推断出的类型是int,会去除&引用 a = 13; // 重新赋值 cout << "i = " << i << " a = " << a << endl; // 输出i=10,a=13 // 只有显式声明是引用& auto &b = r; b = 15; // 重新赋值 cout << "i = " << i << " b = " << b << endl; // 输出i=15,a=15 |
3.使用auto关键字进行类型推导时,编译器会自动忽略顶层const,除非显示声明。
1 2 3 4 5 6 7 8 9 |
const int a = 10; auto b = a; //auto自动推断类型是 int a = 12; // 报错,a为const int类型,无法修改const变量 b = 15; // 正确,b为int类型 // 显示声明 const auto c = a; c = 10; // 报错,c为const int类型,无法修改const变量 |
4.对于数组类型,auto关键字会推导为指针类型,除非被声明为引用。
1 2 3 4 5 6 |
int a[10]; auto b = a; //auto推断为 int*指针类型 cout << typeid(b).name() << endl; // 输出:int * auto &c = a; //显示声明& auto推断为 int[10]类型 cout << typeid(c).name() << endl; // 输出:int [10] |
Amazing loads of beneficial information. diflucan 150 mg
Nicely put. Kudos! https://viagrapython.com/
Whoa all kinds of very good information! buy cialis pills
Fine info. Cheers. viagra for women
You revealed that well. where to buy cbd oil online
You actually mentioned this well! https://viagrapycharm.com/
Superb information. Thanks! Provigil Cognition
Nicely put. Appreciate it! glucophage metformin
Regards, Very good information! ez kratom
Terrific content. Thanks a lot! canadian drugs
You actually suggested it very well! pharmacie canadienne
You have made your point! cbd hemp oil
Nicely put, Kudos! kratom for sale
This is nicely expressed! ! Prednisone Study Ut Southwest
Fine information. Regards! canada drug pharmacy
Fantastic data, Cheers. Provigil Copay Card
Thanks. Excellent information. she gives him viagra
This is nicely expressed! ! generic viagra no doctor prescriptions
Kudos! Loads of stuff.
northwest pharmaceuticals canada