跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

C++ 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修饰,而保留修饰指向对象的constconst 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::iterator it = vec.begin(); it! = vec.end(); it++){cout<<"vec:"<< *it <使用auto自动类型推导后对容器的遍历:for(auto it = vec.begin(); it! = vec.end(); it++ ){cout>>"vec:"<<*it<是不是清爽了很多,利用auto自动类型推导,就不需要写一堆迭代器类型了。

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

(3)用于函数的返回值类型后置:和decltypr配合使用,在后文讲述。

到此这篇关于C++ auto自动类型推导规则和使用详解的文章就介绍到这了,更多相关C++自动类型推导内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:深入解析C++中的auto自动类型推导C++11之自动类型推导的实现示例

相关文章