1. auto类型推导
下面是auto的使用举例:
-
auto x =5; //正确,x是int类型 auto pi = new auto(1); //正确,批是int* const auto* v = &x, u = 6; //正确,v是const int*类型,u是const int static auto y = 0.0; //正确,y是double类型 auto int r; //错误,auto不再表示存储类型的指示符 auto s; //错误,auto无法推导出s的类型(必须马上初始化)
auto并不能代表一个实际的类型声明(上面s编译错误),只是一个类型声明的“占位符”。使用auto声明的变量必须马上初始化,以让编译器推断出它的类型,并且在编译时将auto占位符替换为真正的类型。
2. auto类型推导规则
-
int x = 0; auto *a = &x; //a->int*,auto被推导为int auto b = &x; //b->int*,auto被推导为int* auto &c = x; //c->int&,auto被推导为int auto d = c; //d->int, auto被推导为int const auto e = x; //e->const int auto f = e; //f->int const auto& g = x; /