C++11新功能

新类型:
C++11新增了long long和unsigned long long以支持64位的整形;
统一的初始化
C++11扩大了用大括号括起的列表(初始化列表)的适用范围,使其可用于所有内置类型和用户定义的类型(即类对象)。使用初始化列表时,可添加等号,也可以不添加:

int x={
    
    5};
double y{
    
    2.75}
short quar[5] {
    
    4,5,2,76,1}

初始化列表也可用于new表达式中:

int * ar=new int[4]{
    
    2,4,6,7};

创建对象时,也可使用大括号(而不是圆括号)括起来的列表来调用构造函数:

class Stump
{
    
    
private:
	int roots;
	double weight;
public:
	Stump(int r,double w):roots(r),weight(w){
    
    }
}

Stump s1(3,15.6)//old style
Stump s2{
    
    5,43.4}//C++11
Stump s3={
    
    4,32.1}//C++11

C++11提供了多种简化声明的功能,尤其在使用模板的时候;
1.auto
在C++11中,auto被用于实现自动类型推断进行显示初始化,让编译器能够将变量的类型设置为初始值的类型:

auto maton=112;//maton的类型被自动显示初始化为int
auto pt=&maton;//pt的类型被自动推断为int*
double fm(double,int);
auto pf=fm;//pf的类型被自动推断为double(*)(double,int)

auto还可以简化模板声明:

for(std::initializer_list<double>::iterator p=il.begin();p!=il.end;p++)

可以替换为:

for(auto p=il.begin();p!=il.end();p++)

2.decltype
关键字decltype将变量的类型声明为表达式指定的类型。下面的语句的含义是,让y的类型与x相同,其中x是一个表达式:

decltype(x) y;

该关键字在定义模板时特别有用,因为只有等到模板被实例化时才能确认类型:

template<typename T,typename U>
void ef(T t,U u)
{
    
    
	decltype(T*U) tu;
}
**```
3.返回类型后置**
C++11新增了一种函数声明语法:在函数名和参数列表后面(不是前面)指定返回类型:

```cpp
double f1(double,int);
auto f2(double,int)->double;

就常规函数的可读性而言,这种新语法好像是倒退,但能够使用decltype来指定模板函数的返回类型。

おすすめ

転載: blog.csdn.net/weixin_42105843/article/details/121161672