码迷,mamicode.com
首页 > 编程语言 > 详细

一起学习c++11——c++11中的新语法

时间:2016-07-14 02:43:26      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

c++11新语法1: auto关键字
c++11 添加的最有用的一个特性应该就是auto关键字。
不知道大家有没有写过这样的代码:

std::map<std::string, std::vector<std::shared_ptr<std::list<T> > > > map;
std::map<std::string, std::vector<std::shared_ptr<std::list<T> > > >::iterator it = map.begin();


甚至比这个更复杂的模板嵌套。
这种情况下,不但代码冗长,而且容易出错,出错之后的编译错误提示信息也难以阅读
而使用auto则可以大幅的简化代码的编写,也减少拼写出错的可能

std::map<std::string, std::vector<std::shared_ptr<std::list<T> > > > map;
auto it = map.begin();

 


c++11新语法2: nullptr
在没有nullptr之前,空指针的定义如下:

#ifdef __cplusplus   
#define NULL    0   
#else   
#define NULL    ((void *)0)   
#endif   

因为C++是强类型的,void *是不能隐式转换成其他指针类型的,所以c++的NULL被直接定义为0.
这种情况下有个很扯的错误就是

void foo(int i);  
void foo(char* p) ;

这种情况下:

foo(NULL);

是不明确的。
所以在c++11中引入了nullptr

foo(0);
foo(nullptr);

解决了这个问题。


c++11新语法2: for循环
c++中常规的for循环如下:

std::vector<int> v;
for(auto it = v.begin(); it != v.end(); it++){
    //do anything
}

其他语言,比如python中的for循环是这样的

for var in list:
    #do anything

cpper会不会感到忧郁?
所以c++11引入了这个:

for(auto v : vector){
    // do anything
}

 


以上就是c++11中最常用的一些新语法。

 

abelkhan技术论坛:http://abelkhan.com/forum.php,欢迎大家交流技术

一起学习c++11——c++11中的新语法

标签:

原文地址:http://www.cnblogs.com/qianqians/p/5668573.html

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