文章目录
1、简介
使用了 auto 关键字以后,编译器会在编译期间自动推导出变量的类型,这样我们就不用手动指明变量的数据类型了。
auto 关键字基本的使用语法如下:
auto name = value;
auto 仅仅是一个占位符,在编译器期间它会被真正的类型所替代。或者说,C++ 中的变量必须是有明确类型的,只是这个类型是由编译器自己推导出来的。
auto n = 10; // 10 是一个整数,默认是 int 类型,所以推导出变量 n 的类型是 int
auto f = 12.8; // 12.8 是一个小数,默认是 double 类型,所以推导出变量 f 的类型是 double
auto p = &n; // &n 的结果是一个 int* 类型的指针,所以推导出变量 p 的类型是 int*
auto url = "http://c.biancheng.net/cplus/"; // 由双引号""包围起来的字符串是 const char* 类型,所以推导出变量 url 的类型是 const char*,也即一个常量指针
auto 除了可以独立使用,还可以和某些具体类型混合使用,这样 auto 表示的就是“半个”类型,而不是完整的类型。如下:
int x = 0;
auto *p1 = &x; // p1 为 int *,auto 推导为 int
auto p2 = &x; // p2 为 int*,auto 推导为 int*
auto 和 const 的结合:
int x = 0;
const auto n = x; //n 为 const int ,auto 被推导为 int
auto f = n; //f 为 const int,auto 被推导为 int(const 属性被抛弃)
const auto &r1 = x; //r1 为 const int& 类型,auto 被推导为 int
auto &r2 = r1; //r1 为 const int& 类型,auto 被推导为 const int 类型
最后我们来简单总结一下 auto 与 const 结合的用法:
当类型不为引用时,auto 的推导结果将不保留表达式的 const 属性;
当类型为引用时,auto 的推导结果将保留表达式的 const 属性。
2、auto 的限制
2.1 不能有二义性
如:
auto a = 10, b = 12.3; // 是错误的,a 被推断为 int ,而 b 不能为double
2.2 使用 auto 的时候必须对变量进行初始化
2.3 auto 不能在函数的参数中使用
因为参数中未进行初始化,这与第二条是矛盾的。
2.4 auto 关键字不能定义数组
比如下面的例子就是错误的:
2.5 auto 不能作用于类的非静态成员变量
也就是不能作用于类的 没有 static 关键字修饰的 成员变量中。
char url[] = "http://c.biancheng.net/";
auto str[] = url; // url 为数组,所以不能使用 auto
3、auto 的应用
3.1 auto 常用于简化代码
例如:
#include <vector>
using namespace std;
int main(){
vector< vector<int> > v;
vector< vector<int> >::iterator i = v.begin();
return 0;
}
定义迭代器 i 的时候,类型vector< vector<int> >::iterator
书写比较冗长,容易出错。有了 auto 类型推导,只写一个 auto 即可。
auto i = v.begin(); // 使用 auto 代替具体的类型
还有一些平时自定义的很长的类型,也可以用 auto 代替。
3.2 auto 用于泛型编程
当我们不知道变量是什么类型,或者不希望指明具体类型的时候,比如泛型编程中,可以使用 auto 来作为变量的类型。
4、参考
http://c.biancheng.net/view/6984.html