温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++ auto自动类型推导规则是什么及怎么使用

发布时间:2022-08-18 09:20:33 来源:亿速云 阅读:182 作者:iii 栏目:开发技术

这篇文章主要介绍“C++ auto自动类型推导规则是什么及怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C++ 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配合使用。

关于“C++ auto自动类型推导规则是什么及怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI