auto:
声明的变量要进行初始化
1普通变量
auto a=10; //就是根据后面的值->推导前面的定义
cout<<typeid(a).name()<<endl; //通过typeid获得对象a的类型 输出int
2引用和指针
auto a=10;
auto b=&a; //int * 等价于:auto *b我认为这么做的目的是好区分
auto c=&b; //int ** 等价:同上
auto& c=a; //int&
3const修饰
重点:当变量不是指针和引用,auto不会保留const和volatile关键字,反之即可
int a = 10;
const auto b = a; //const int
auto c = b; //int
auto& d = b; //const int&
auto e = &b; //const int*
这两行代码自己理解一下 不懂:const专题
const int* const e = &a;
*e = 100; e = &x; //全err
const int const* f = &a;
*f = 1000; f = &x; //后err
4auto二义性
auto a = 10, b = 1.3; //err
不能用auto的场景
1函数形参:因为auto必须给变量赋值,相矛盾
2非常量静态成员
class A {
public:
//auto a = 0; //err
//static auto b = 1; //err 在我们类中静态成员变量要在全局区::方式初始化
const static auto c = 1; //Yes
};
3数组
int arr[] = {1,2,3,4,5};
auto a = arr; //ok auto:int*
//auto arr[] = arr; //err
//auto arr[10] = {}; //err
4模板
template <class T>
class person{};
void f()
{
person<int> a;
person<auto> b; //err
}
auto方便之处
1STL 容器遍历
//很繁琐
vector<int>v = { 1,2,3,4,5,6,7,8,9 };
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
cout << *it;
//new
for (auto it : v)
cout << it;
2泛型编程
#include<iostream>
using namespace std;
class A {
public:
static string show()
{
return "hello future";
}
};
class B {
public:
static int show()
{
return 123;
}
};
template<class T>
void f()
{
auto i = T::show();
cout << i << endl;
}
int main()
{
f<A>();
f<B>();
return 0;
}