auto使用总结

引入

在C++11之前,auto用于显示地指出变量为自动存储,该方式很少被使用到。到了C++11,该关键字被重新定义,使其能够用于自动类型推断,该过程在编译阶段完成。

基本用法
  • 自动类型推导
auto a = 10;//type of a is int
auto b = 10.0;//type of b is double
auto c = &a;//type of c is int *
  • 简化代码,对于复杂类型,使用auto关键字可以简化代码
std::vector<std::pair<int, std::string>> vec;
auto it = vec.begin(); // type of it is std::vector<std::pair<int, std::string>>::iterator
  • 结合其他特性使用,如lambda表达式和范围for循环
auto function=[](int a,int b){return a+b;};
std::vector<int> v;
for(auto elem:v){
    std::cout<<elem<<std::endl;
}
注意事项
  • 当auto用于连续定义多个变量时,变量类型要保持一致
auto e = 10 , f = 10;//correct
auto g = 10 , h = 10.0;//error,对于此实体“auto”类型是 double,但之前默示为 int
  • 使用auto时必须要对变量进行初始化
auto i;//error,无法推导“auto”类型(需要初始值设定项)
  • 在C++11中,auto不能在函数的参数中使用,在函数参数中,变量类型只进行了声明,只有在实际调用函数的时候才会给参数赋值,而auto要求必须对变量进行初始化,这是矛盾的
void func(auto c){
}
  • auto不能用于声明数组
auto arr[4]={1,2,3,4};//error,“auto”类型不能出现在顶级数组类型中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值