码迷,mamicode.com
首页 > 其他好文 > 详细

auto类型

时间:2014-11-12 10:29:02      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   使用   sp   数据   div   

http://blog.csdn.net/huang_xw/article/details/8760403

自动类型推断

    auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作

 

#include <vector>
#include <map>

using namespace std;

int main(int argc, char *argv[], char *env[])
{
// 	auto a;                 // 错误,没有初始化表达式,无法推断出a的类型
// 	auto int a = 10;        // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。

	// 1. 自动帮助推导类型
	auto a = 10;
	auto c = ‘A‘;
	auto s("hello");

	// 2. 类型冗长
	map<int, map<int,int> > map_;
	map<int, map<int,int>>::const_iterator itr1 = map_.begin();
	const auto itr2 = map_.begin();
	auto ptr = []()
	{
		std::cout << "hello world" << std::endl;
	};

	return 0;
};

// 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,
// 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。
template <class T, class U>
void Multiply(T t, U u)
{
    auto v = t * u;
}

 我们可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto

定义在堆上的变量,使用了auto的表达式必须被初始化,auto* y = new auto(9); // Fine. Here y is a int* 

 

auto类型

标签:style   blog   http   color   ar   使用   sp   数据   div   

原文地址:http://www.cnblogs.com/notlate/p/4091302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!