您的位置:首页 > 编程语言 > C语言/C++

[c++]c++11 新标准

2015-10-16 16:25 387 查看
1. constexpr

要求编译器去确认变量是常量表达式

constexpr int sz=size(); //编译时除非size()是constexpr function,否则不通过


当用constexpr修饰指针,说明是指针常量,不是指向常量的指针

const int *p=nullptr; //指向常量的指针
constexpr int *q=nullptr;//指针常量


2. alias declaration

using SI=Sales_item;// similar to typedef  Sales_item SI;


3. auto

编译器自动根据表达式的结果推测变量类型

auto忽略top-level const, low-level const保留

int a=10;
const int * const p=&a;
auto pp=p;// pp is const int *  指向常量的指针,top-level const需要在auto前面加上 const
const auto pp=p;


4. decltype

当我们只想用编译器从表达式中推测出来的类型,而不是用表达式来初始化这个类型(like auto),就用decltype

decltype(f()) sum=x;


decltype同时保留了top-level和low-level的const

5.类中初始化器

{}或者= ,()不行。

class book{
string isbn;
double price{0.0};
int piece=0;
};


6. range for statement

for(declaration : expression)

statement;

//example
string str("some string");
decltype(str.size()) count=0;
for(auto c: str)
if(isspace())
count++;

//if need to change the element in str using auto &
for(auto &c:str)
c=toupper(c);


7. vector 用花括号初始化

vector<string> strs={"erd","sdg","acv"};//再也不用一个一个push_back()啦

花括号不能用()代替
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: