学习笔记:
1.初始化后,才可以自动推导
auto x = 3.14; // x 是浮点型 double
auto y = 520; // y 是整形 int
auto z = 'a'; // z 是字符型 char
auto nb; // error,变量必须要初始化
auto double nbl; // 语法错误, 不能修改数据类型
———————————————————————————————————————————
2.
①当变量不是指针或者引用类型时,推导的结果中不会保留const、volatile关键字
②当变量是指针或者引用类型时,推导的结果中会保留const、volatile关键字
int temp = 110;//temp是int型
auto *a = &temp;//&temp是temp的地址,指向地址的只能是指针,所以auto为int,int*表示指针
auto b = &temp;//&temp是temp的地址,指向地址的只能是指针,所以auto为int*,表示指针
auto &c = temp;//auto推导为int,c为temp的别名,修改c,temp也改变
int tmp = 250;//tmp是int型
const auto a1 = tmp;//a1是const int型,auto推导为int
//理论上a2也是const int型,但当变量不是指针或者引用类型时,推导的结果中不会保留const、volatile关键字
//所以auto推导为int,所以a2是int型
auto a2 = a1;
const auto &a3 = tmp;//tmp是int型,a3为const int&型,auto为int
//当变量是指针或者引用类型时,推导的结果中会保留const、volatile关键字
//a3为const int &型,所以a4也为const int&型,auto推导为const int
auto &a4 = a3;
//a1是const int型,所以pt4是int*型,但const要保留,所以pt4是const int*型
//const int*中const表示的是指向的值不可修改,但地址可以修改,所以*pt4=100不可实现
auto *pt4 = &a1;
———————————————————————————————————————————
3.不能用于类的非静态成员变量的初始化
class Test
{
auto v1 = 0; // error
static auto v2 = 0; // error,类的静态非常量成员不允许在类内部直接初始化
static const auto v3 = 10; // ok,静态+常量,常量在定义的时候就会初始化,而不是构建类时再初始化
}
———————————————————————————————————————————
4.不能使用auto关键字定义数组
———————————————————————————————————————————
5.无法使用auto推导出模板参数
template <typename T>
struct Test{}
int func()
{
Test<double> t;
Test<auto> t1 = t; // error, 无法推导出模板类型
return 0;
}
———————————————————————————————————————————
6.auto用于STL的容器遍历
map<int, string> person;
for (auto it = person.begin(); it != person.end(); ++it)
{
}
———————————————————————————————————————————
7.用于泛型编程
,在使用模板的时候,很多情况下我们不知道变量应该定义为什么类型
#include <iostream>
#include <string>
using namespace std;
class T1
{
public:
static int get()
{
return 10;//返回整型
}
};
class T2
{
public:
static string get()
{
return "hello, world";//返回字符串
}
};
template <class A>
void func()
{
auto val = A::get();
cout << "val: " << val << endl;
}
int main()
{
func<T1>();
func<T2>();
return 0;
}