前言
C++是一种强类型语言,声明变量时必须明确指出其类型。但是,在实践中,优势我们很难推断出某个表达式的值的类型,尤其是随着模板类型的出现,要想弄明白某些复杂表达式的返回类型就变得更加困难。为了解决这个问题,C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。
一、自动类型推断
auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。
#include#include
二、返回值占位
立即学习“C++免费学习笔记(深入)”;
templateauto compose(T1 t1, T2 t2) -> decltype(t1 + t2) { return t1+t2; } auto v = compose(2, 3.14); // v's type is double
三、使用注意事项
1、我们可以使用valatile,pointer(*) ,reference(&) ,rvalue reference(&&) 来修饰auto
auto k = 5; auto* pK = new auto(k); auto** ppK = new auto(&k); const auto n = 6;
初次使用易达CMS企业系统以下简称(易达),易达系统运行于微软公司开发的 ASP 程序平台,ASP是目前国内应用最广泛的WEB开发语言,空间基于微软windows IIS,使您的购买空间和维护成本降到最低,并以其众多独创或领先的新特性和功能设计,使得用户深刻体验到易达以原创研发、服务客户为主导开发理念的独到之处和领先优势,易达严格上讲是为懂点网站建设和HTML或DIV+CSS技术的人员而开发的一套
2、用auto声明的变量必须初始化
auto m; // m should be intialized
3、auto不能与其他类型组合连用
auto int p; // 这是旧auto的做法。
4、函数和模板参数不能被声明为auto
void MyFunction(auto parameter){} // no auto as method argument
template // utter nonsense - not allowed
void Fun(T t){}
5、定义在堆上的变量,使用了auto的表达式必须被初始化
int* p = new auto(0); //fine int* pp = new auto(); // should be initialized auto x = new auto(); // Hmmm ... no intializer auto* y = new auto(9); // Fine. Here y is a int* auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)
6、以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid
int value = 123; auto x2 = (auto)value; // no casting using auto auto x3 = static_cast(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<总结
以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用C++能有一定的帮助,如果有疑问大家可以留言交流。
更多C++11新特性之auto的使用相关文章请关注PHP中文网!










