1.auto的功能:
auto 可以自动推理数据类型。
使用语法如下:
#include<iostream> #include<typeinfo> using namespace std; int main() { //auto变量定义时必须初始化 auto x = 3; auto y{23}; //auto c; //定义一个auto的系列的变量必须始终推倒成同一类型 auto x1{1}, x2{2}; //auto a{10}, b{2.0}; //如果初始化表达式是引用或const,则去除引用或const语义 int& q{x1}; auto m {q}; cout<<"type of m: "<< typeid(m).name() <<endl; //int m = 400; cout<< "q : " << q << " m : " << m <<endl; const int n{100}; auto t {n}; cout<<"type of t: "<< typeid(t).name() <<endl; //int t = 300; cout<<"t : "<< t <<endl; //如果auto关键字加上&,则不去除引用或const语意 char ch1{'c'}, &ch2{ch1}; auto& ch3{ch2}; cout<<"type of ch3: "<< typeid(ch3).name() <<endl; //char& ch3 = 'b'; cout<<"ch1 : "<<ch1<<" ch2 : "<<ch2<<" ch3: "<<ch3<<endl; const double h {1.0}; auto& k {h}; cout<< "type of k: "<<typeid(k).name() <<endl; //const double //k = 12.0; //如果初始化为数组,auto自动推倒为指针 int arr[3]{1,2,3}; auto p {arr}; cout<<"type of p: "<<typeid(p).name()<<endl; //int* cout<<"size of arr: "<<sizeof(arr)<<endl; cout<<"size of p: "<<sizeof(p)<<endl; //如果加上&,则推导为数组 auto& px{arr}; cout<<"type of px: "<<typeid(px).name()<<endl; //A3_i cout<<"size of px: "<<sizeof(px)<<endl; //C++14可以用auto来推倒函数返回值 return 0; }
注:auto不能用来定义数组或函数形参。
2.使用场景:
第一种经典场景:当变量的数据类型很复杂或者写起来很麻烦,我们懒得打字了,其实是为了加快编程效率。
list<string> c; list<string>::iterator ite; ite = find(c.begin(), c.end(), target); //代替为下面 list<string> c; auto ite = find(c.begin(), c.end(), target);
第二种经典场景: 当我们有时不确定函数返回值类型时, 或者说用auto来推理函数返回值类型。
template<typename T> auto func(T a, T b){ return max(a,b); } int main() { cout << func(100,200) <<endl; cout << func(300.88, 400.55) <<endl; cout << func('a', 'A') << endl; return 0; }