auto
auto 的自动类型推导,用于从初始化表达式中推断出变量的数据类型。从这个意义上讲,auto并非一种“类型”声明,而是一个类型声明时的“占位符”,编译器在编译时期会将 auto 替换为变量实际的类型。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
float foo() {}
void func(vector<string> & tmp)
{
//4.推到容器的类型,auto自动推到类型为vector<string>,写起来方便
for (auto i = tmp.begin(); i < tmp.end(); i++)
{
// 函数体
}
}
int main()
{
//1.推到变量的类型
auto x = 1; // x的类型为 int
//2.推到函数返回值的类型
auto y = foo(); // y 的类型为 float
//3.推到自定义结构体的类型
struct Test
{
int i;
}str;
auto str1 = str; // str1 的类型是 struct Test
return 0;
}
注意点:
1.定义变量时,必须初始化
2.VS2017 不支持函数形参是auto变量
3.auto变量不能作为自定义类型的成员变量,初始化了了也不行
4.auto不能用于数组,不能auto数组
5.模板实例化不能使auto类型,初始化了也不行