一、auto是什么?
auto是类型标示符,编译器在编译阶段推导变量的类型。(并不会导致运行程序效率降低)
二、auto能干什么?
1、 代替冗长的变量声明。
2、用于声明函数返回值类型
三、auto的使用用例
using namespace std;
auto getStr(){
return "hello";
}
int main(){
auto str="abc";
cout << str << endl;
cout << getStr() <<endl;
}
四、auto的注意事项
1、auto声明的变量必须初始化
auto aa;
aa="str";
cout << aa <<endl
2、声明指针类型时,可以省略*,但是声明引用时必须添加&(否则不能申明成引用,而是默认变量类型)
auto str1="abc";
auto * p1=&str1;
cout << *p1 << endl;
auto p2=&str1;
cout << *p2 << endl;
3、auto 不能用来声明参数和数组
#include <iostream>
using namespace std;
auto getStr(auto name){
return name;
}
int main(){
cout << getStr("hello") <<endl;
}
#include <iostream>
using namespace std;
int main(){
int arr1[3]={1,2,3};
auto arr2[3]={1,2,3};
}