1、新类型:
long long、unsigned long long、char16_t、char32_t
2、统一的初始化:
C++11扩大了初始化列表的适用范围,使其可用于所有内置类型和用户定义的类型,且使用的时候可以不添加等号:
int x = {5};
double y {3.14};
short quar[5] {4, 5, 2, 76, 1};
int * ar = new int [4] {2, 4, 6, 7};
创建对象时,大括号内容也可用于调用构造函数:
class Stump
{
private:
int roots;
double weight;
public:
Stump(int r, int w) : roots(r), weight(w) {}
};
Stump s1(3, 15.6); //old style
Stump s2{5, 43.6}; //C++11
Stump s3 = {4, 25.6}; //C++11
初始化列表的语法能够防止缩窄,常规初始化会允许程序员执行没有意义的赋值操作,例如“char c = 1.314”,然而使用初始化列表语法,编译器会禁止这样的类型转化,但允许将值转换为更宽的类型,另外只要值在较窄类型的取值范围内,此时的“缩窄”也是允许的。
C++11提供了模板类 initializer_list,如果类有接受 initializer_list 作为参数的构造函数,则初始化列表语法只能用于该构造函数。列表中的元素必须是同一类型或能转化为同一类型,。例如STL容器就提供了将 initializer_list 做为参数的构造函数:
vector<int> a1(10); // uninitialized vector with 10 elements
vector<int> a2{10}; // initializer_list, a2 has 1 element set to 10
vector<int> a3{4, 6, 1}; // 3 elements set to 4,6,1
头文件 initializer_list 提供了对模板类 initializer_list 的支持。这个类包含成员函数 begin() 和 end() ,可用于获悉列表的范围:
#include <initializer_list>
double sum(std::initializer_list<double> il);
int main()
{
double total = sum({2.5, 3.1, 4});
...
}
double sum(std::initializer_list<double> il)
{
double tot = 0;
for (auto p = il.begin(); p != il.end(); p++)
tot += *p;
return tot;
}
3、声明:
C++11提供了多种简化声明的功能,尤其是在使用模板时。
1、auto:
auto在C++11中用于自动类型推断,这要求进行显式初始化,让编译器能够将变量的类型设置为初始值的类型:
auto maton = 112; // maton is type int
auto pt = &maton; // pt is type *int
double fm(double, int);
auto pf = fm; // pf is type 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 将变量的类型声明为表达式指定的类型;这在定义模板的时候相当有用,因为只有等到模板被实例化才能知道其类型:
template<typename T, typename U>
void ef(T t, U u)
{
decltype(T * U) tu;
...
}
3、返回类型后置:
C++11新增了一种函数声明语法,将函数的类型后置声明:
auto f1(double, int) -> double; // new syntax, return type is double
这种语法看起来是可读性的倒退,但实际上,它使得我能够使用 decltype 来指定模板函数的返回类型:
template<typename T, typename U>
auto eff(T t, U u) -> decltype(T * U);
{
...
}
因为在编译器遇到 eff 的参数列表之前,T 和 U 还不在作用域内,因此必须在参数列表后使用 decltype。
4、模板别名:using=
对于冗长或复杂的标识符,如果能为其创建别名将会很方便,C++提供了 typedef 实现这个功能:
typedef std::vector<std::string>::iterator itType;
C++11提供了一种新语法实现:
using itType = std::vector<std::string>::iterator;
区别在于,在模板内无法使用 typedef,但是可以使用 using= 语法
template<typename T>
using arr12 = std::array<T, 12>;
5、空指针:nullptr

被折叠的 条评论
为什么被折叠?



