1.auto类型推导的语法和规则
C++11 赋予 auto 关键字新的含义,使用它来做自动类型推导。也就是说,使用了 auto 关键字以后,编译器会在编译期间自动推导出变量的类型,这样我们就不用手动指明变量的数据类型了。
auto 关键字的使用:还有一个值得注意的地方是:使用 auto 类型推导的变量必须马上初始化,这个很容易理解,因为 auto 在 C++11 中只是“占位符”,并非如 int 一样的真正的类型声明。
auto test = 2;
auto n = 10; // int
auto f = 12.8; // double
auto p = &n; // int *
auto url = "http://c.biancheng.net/cplus/"; // 常量指针 const char*
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 仅仅占用一个字符位,在编译期间会被真正的类型代替
最后我们来简单总结一下 auto 与 c