C++11新特性之auto的使用

2020-01-06 16:01:35王振洲

6、以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid


int value = 123; 
auto x2 = (auto)value; // no casting using auto 
 
auto x3 = static_cast<auto>(value); // same as above 

7、定义在一个auto序列的变量必须始终推导成同一类型


auto x1 = 5, x2 = 5.0, x3='r'; // This is too much....we cannot combine like this 

8、auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型


const int i = 99; 
auto j = i; // j is int, rather than const int 
j = 100 // Fine. As j is not constant 
 
// Now let us try to have reference 
auto& k = i; // Now k is const int& 
k = 100; // Error. k is constant 
 
// Similarly with volatile qualifer 

9、auto会退化成指向数组的指针,除非被声明为引用


int a[9]; 
auto j = a; 
cout<<typeid(j).name()<<endl; // This will print int* 
 
auto& k = a; 
cout<<typeid(k).name()<<endl; // This will print int [9] 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用C++能有一定的帮助,如果有疑问大家可以留言交流。


注:相关教程知识阅读请移步到C++教程频道。