Chinaunix首页 | 论坛 | 博客
  • 博客访问: 287854
  • 博文数量: 148
  • 博客积分: 4365
  • 博客等级: 上校
  • 技术积分: 1566
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 21:38
文章分类
文章存档

2014年(2)

2013年(45)

2012年(18)

2011年(1)

2009年(54)

2008年(28)

我的朋友

分类: C/C++

2013-01-24 23:04:42

对照着cpp primer 5th 中所列的c++ 11特性按章节学习记录下。

Chapter 2 Variables and Basic Types

1. 新类型 long long,at least as large as long,这个怎么记得早就有了,vs2005好像就支持。

2. List Initialization

   int i{3}; //用大括号(curly braces)的形式,使用范围比较受限,SBL这里只简单提了下,后面讲类估计会有

   用浮点初始化整形这种不行,loss infomation

   但 int->short这种可以,数据截断truncate

3. 空指针 nullptr, 任何指针都可以用其初始化,没看出和NULL有区别,难道为了省一个头文件和预编译期的宏处理。

4. 关于const,提到了 top-level和low-level,记得4th好像没出现过

   top-level:指对象本身是const的;low-level:指针或引用所指向对象。下面有几个例子,引用都是low-level的

int *const p1 = &i;  // we can't change the value of p1; const is top-level
const int ci = 42;   //  top-level
const int *p2 = &ci; // we can change p2; const is low-level
const int *const p3 = p2; // right-most const is top-level, left-most is not
const int &r = ci;  // const in reference types is always low-level

区别:复制一个对象时top-level的const可以被忽略(ignore),上面的变量赋值:

int i = ci;  // ok
p2 = p3; // ok

但是low-level的不行,赋值的两者要求low-level const属性相同,或者可以进行nonconst->const转换

int *p = p3; // error: p3 has a low-level const but p doesn't
p2 = p3;     // ok: p2 has the same low-level const qualification as p3
p2 = &i;     // ok: we can convert int* to const int*
int &r = ci; // error: can't bind an ordinary int& to a const int object
const int &r2 = i; // ok: can bind const int& to plain int

5. constexpr关键字,告诉编译器该表达式是个常量,在定义数组的时候比较有用。不适用于IO对象及类类型。

constexpr int * p = nullptr; //这里相当于const作用在p上,即top-level const,虽然看上去像是作用在*p上。

6. 类型别名(type alias) 除了过去的typedef,现在可以使用using语句,比如

using IV = vector; //gcc4.6 和vs2010都失败了,看来都要最新版本

7. auto关键字,只要提供初始化的表达式,变量类型交给编译器去推断

int i,j;//i=...,j=...

auto k = i+j, *p = &i; //k:int  p: int*

但是不同类型的不能放在一条语句中

auto k2 = i*j, k3 = 3.14;// error k3是float,不是int

auto也不是完全的仍给啥类型就定义啥类型

(1)引用这种间接类型,出来的是直接类型

int &r = i; auto r2 = r; //r2 是个int 不是 int&

(2)直接用变量赋值时,top-level const属性被忽略,最后一个稍微有点绕

const int ci = i, &cr = ci;
auto b = ci;  // b is an int (top-level const in ci is dropped)
auto c = cr;  // c is an int (cr is an alias for ci whose const is top-level)
auto d = &i;  // d is an int*(& of an int object is int*)
auto e = &ci; // e is const int*(& of a const object is low-level const)

想要const,就这样 const auto ...

一条语句中的变量,其const属性编译器deduces出的结果必须一致,像上面的k,p其const属性要求一致。

8. decltype关键字,这个更强大,等看完函数那节好好总结下。

9. 结构内数据变量初始化

struct base
{
	int i =3;
};

很遗憾,又都编译失败了,提示只有静态变量才可以,让人升级到4.7啊这是。

阅读(649) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~