auto的基本概念
在C++11标准的语法中,auto被定义为自动推断变量的类型
auto的作用就是为了简化变量初始化,如果这个变量有一个很长很长的初始化类型,就可以用auto代替
- 用auto声明的变量要初始化(auto是根据后面的值来推测这个变量的类型,如果后面没有值,自然会报错)
auto ra; //错误
auto a = 1; //正确
- auto不能作为函数的参数和不能用来声明数组(原因同上)
int Add(auto a, int b) //错误
{
return (a + b);
}
auto a[] = { 1,2,3,40 }; //错误
- 可以用来作函数返回值,但声明和定义不能分开
#include<iostream>
using namespace std;
auto add(); //错误
int main()
{
cout << add();
return 0;
}
auto add()
{
double tmp = 2.4;
return tmp;
}
#include<iostream>
using namespace std;
auto add() //没报错
{
double tmp = 2.4;
return tmp;
}
int main()
{
cout << add();
return 0;
}
- 可以使用typeid来查询 auto所替代的类型
auto a = 1, b = 2;
cout<<typeid(a).name();
使用auto也能在一条语句中声明多个变量
但是因为一条声明语句只能有一个基本数据类型,所以该语句中所有变量的数据类型都必须一样
auto a = 1, b = 2; //正确,为int类型
auto ra = 3, rra = 3.43;//错误,一个double,一个int类型
错误演示
在使用 auto的时候要注意返回值类型
string s = "abcd";
for (auto i = s.size()-1; i >= 0; i--) //size()返回的是unsigned int类型,没有负数
{
cout << s[i] << endl;
}
不能用于类的非静态成员变量的初始化
class Test
{
auto a = 0;//error
static auto b = 2;//error 带有类内初始化表达式的 静态数据成员 必须具有不可变的常量整型类型,或必须被指定为“内联”
static const auto c = 10;//ok
};
auto的经典应用:for循环语句
对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围。
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1,2,3,4,5 };
for (auto i : a)
{
cout << i << ' ';
}
return 0;
}
刚才举的例子中的变量i实质是数组a中每个元素的一个拷贝
如果要通过变量i修改数组中变量的值,变量i必须声明成引用类型。
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1,2,3,4,5 };
for (auto& i : a)
{
i *= 2;
}
for (auto i : a)
{
cout << i << ' ';
}
return 0;
}
范围for语句的遍历对象除了是数组和容器之外,还可以是用一对花括号括起来的初始值列表
#include<iostream>
using namespace std;
int main()
{
for (auto i : {1,2,3,4,5})
{
cout << i << ' ';
}
return 0;
}