c++11新特性 auto的使用

       C语言里面其实就已经有auto关键字了,只不过很少用到
当我们在C或者以前的C++中,auto关键字在自动存储类中声明变量,即具有局部生存期的变量,
基本上可以被无视。比如这个局部变量: int a = 100; auto int a = 100;并没有什么区别,
但是在C++11标准里面auto已经有了新的含义,可以从声明的初始化表达式中可以推导出变量的类型。
auto a = 100;等价int a = 100;

在c++11中auto有两个新特性就是:自动类型推断和返回值占位,如下面的列子

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <map>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	//自动类型推断
	auto A = 10;  //equal int a=10;
	auto B = 'A';
	auto C("hello");
	cout<<A<<B<<C<<endl;
	// 类型冗长
	map<int, map<int,int> > myMap;
	map<int, map<int,int>>::const_iterator itr1 = myMap.begin();
	const auto itr2 = myMap.begin();   //itr2 equal itr1;
	
	getchar();
	return 0;
}


返回值占位

   当我们不知道返回值的类型时这将是一个很炫的技能

   decltype 不会执行表达式而auto会decltype 仅仅推论一下表达式的类型

template <typename Type1, typename Type2>  
auto compose(Type1 t1, Type2 t2) -> decltype(t1 + t2)  
{  
	return t1+t2;  
}  
auto v = compose(10, 3.141); // v's type is double  


auto使用时需要注意的事项

      使用时必须初始化

auto A = 10;  //ok, equal int a=10;
auto B ; //bad, B shuld be intialized
        同一序列上必须类型相同

auto A = 10, B = 20;    //ok 
auto A = 10, B = 13.5 ; //bad
       函数和模板参数不能被声明为auto
void MyFunction(auto parameter){}    //bad  

template<auto T>                     // bad  
void Fun(T t){}  </span>
        不能用于类型转化

int tmp = 123;  
auto x1 = (auto)tmp; // bad 
  
auto x2 = static_cast<auto>(tmp); //bad
      指向数组时可定义为引用,否则会退化成指针
int a[9];  
auto j = a;  
 // equal  int* j= a;  
  
auto& k = a;  
//  equal  k[]= a[];</span></span>
 

     auto不能制动推导成const,除非定义为引用类型

const int  i=10;
auto j=i;
j=100;      // ok, j is int

auto &k=i;
k=100;     //  bad, k is const int</span>


















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值