auto关键字
auto的使用
auto的使用细则
auto不能使用的场景
1.auto的使用
在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量 在C++11中,auto具有全新的含义:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推到而得
#include<iostream>
using namespace std;
int TestAuto()
{
return 10;
}
int main()
{
int a = 10;
auto b = a;
auto c = 'a';
auto d = TestAuto();
//auto=e; 使用auto变量时必须进行初始化,否则无法通过编译
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
return 0;
}
结果为
2.auto的使用细则
1.auto与指针和引用结合起来使用
用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时必须加&
#include<iostream>
using namespace std;
void test()
{
int a = 10;
int b = a;
int& ra = a;
//定义指针:*可加可不加
auto pa = &a;//右值&a代表取地址,即使不加&也能判断出pa是一个指针
auto pb = &b;
//定义引用,必须加&
//auto rb=b; 不加&,无法判断出这代表引用的意思,而是一个复制的操作
auto& rb = b;//
auto c = b;
cout << typeid(pa).name() << endl;
cout << typeid(pb).name() << endl;
cout << typeid(rb).name() << endl;
cout << typeid(c).name() << endl;
}
int main()
{
test();
return 0;
}
结果如下
2.在同一行定义多个变量
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器会报错,因为编译器只对第一个类型进行推导。
#include<iostream>
using namespace std;
void TestAuto()
{
int a, b, c, d;
auto a = 1, b = 2;
//一行定义多个变量时类型必须一致
auto c = 3, d = 4.0;
cout << typeid(a).name() << " " << typeid(b).name() << endl;
cout << typeid(c).name() << " " << typeid(d).name() << endl;
}
int main()
{
TestAuto();
return 0;
}
3.auto不能推导的场景
1.auto不能作为函数的参数
//此处编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导
void TeatAuto(auto a)
{}
2.auto不能用来声明数组
void TestAuto()
{
int a[]={1,21,3};
auto b[]={4,5,6};//不能这样使用auto,因为b是一个空数组的话就无法进行判断