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

2023-05-19,

这篇文章主要介绍“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被推导的类型:
1 auto  *a = &x;      a   被推导为 :int * auto 推导为: int
2 auto  b =  &x;      b  被推导为: int* auto 推导为: int *
3 auto &c = x ;      c  被推导为:   int& auto 推导为: int
4 auto d = c;      d 被推导为:  int auto 推导为: int
5 const auto e= x;      e 被推导为: const int auto 推导为:    int
6 auto f = e;      f 被推导为: int auto 推导为:    int
7 const auto& g = x;      g 被推导为: const int& auto 推导为:    int
8 auto& 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自动类型推导规则是什么及怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注本站行业资讯频道,小编每天都会为大家更新不同的知识点。

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

下载本文的Word格式文档,以方便收藏与打印。