『C++』C++11新特性 auto自动类型推导

本文详细介绍了C++中auto关键字的推导规则,包括不推导引用、忽略值类型const、保留引用的const等,并通过实例进行解释。同时,讨论了auto的适用场景,如简化容器迭代器的使用、泛型函数的编写和函数返回值类型后置等,展示了auto如何提升代码的简洁性和可读性。

目录

一.auto推导规则(4点):

二.auto的使用时机


一.auto推导规则(4点):

(1) 引用不是类型,因此auto不能推断出引用

int a = 1;
int& b = a;// b-> int&  用->表示推导出类型,下同
auto c = b;// c->int  

(2)auto 在推断引用的类型时,会直接将引用替换为引用指向的对象。

引用不是对象,任何引用的地方都可以直接替换为引用指向的对象。

int a = 10;
const int& b = a ;// b-> const int&
auto c = b;  //  c-> int 
//相当于 auto c = a; 

由于在传递值时,修改这个值不会对原有的数据造成影响,而传递引用时,修改这个值会对修改原有的数据。

(3)auto 关键字推断类型时,如果没有引用符号,那么会忽略值类型的const修饰,而保留修饰指向对象的const

const int i =1;
auto j = i;//j-> int


int a ;
const int* const pi = &a;//第一个const 修饰指针的指向的对象,第二个const修饰pi指向的值。
                         //会忽略第二个const。
auto pi2 = pi;  // pi2 -> int* const 

(4)如果有引用符号,那么值类型的const和指向的const都会保留

int i = 1;

const int* const j = &i;

auto &k = j; //a->const int const &

 

具体推导例子:        

             int x = 10;

推导表达式:

推导出变量数据类型:auto被推导的类型:
1auto  *a = &x;     a   被推导为 :int *auto 推导为: int
2auto  b =  &x;     b  被推导为: int*auto 推导为: int *
3auto &c = x ;     c  被推导为:   int&auto 推导为: int
4auto d = c;     d 被推导为:  intauto 推导为: int
5const auto e= x;     e 被推导为: const intauto 推导为:    int
6auto f = e;     f 被推导为: intauto 推导为:    int
7const auto& g = x;     g 被推导为: const int&auto 推导为:    int
8auto& h = g;      h 被推导为:const int&auto 推导为:    int

  

注意: auto声明的变量必须马上初始化,因为在编译阶段编译器就将其类型推导出来。

                auto a;error

 

二.auto的使用时机

(1)用于推导容器的迭代器:

 原本不使用类型推导我们对容器的遍历:

for(vector<int>::iterator it = vec.begin(); it! = vec.end(); it++)
{
    cout<<"vec:"<< *it <<endl;
}

使用auto自动类型推导后对容器的遍历:

for(auto it = vec.begin(); it! = vec.end(); it++ )
{
    cout>>"vec:"<<*it<<endl;
}

是不是清爽了很多,利用auto自动类型推导,就不需要写一堆迭代器类型了。

(2)书写泛性函数

不知道程序使用时,传入的参数是什么类型时,用auto可以为我们节省不少工作量。

(3)用于函数的返回值类型后置:

  和decltypr配合使用,在后文讲述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值