c++11 特性

来源:互联网 发布:三菱plc教学软件 编辑:程序博客网 时间:2024/05/16 18:40

1.auto和decltype

C++ 11中引入的auto主要有两种用途:自动类型推断和返回值占位。

template <typename T1, typename T2>auto compose(T1 t1, T2 t2) -> decltype(t1 + t2){   return t1+t2;}
函数后面的 ->decltype(t1 + t2)函数返回值 后置 类型声明。

2.nullptr

   是std::nullptr_t类型的值,用来指代空指针。nullptr和任何指针类型以及类成员指针类型的空值之间可以发生隐式类型转换,同样也可以隐式转换为bool型(取值为false)。但是不存在到整形的隐式类型转换。

3.begin()和end()

egin()和end()。begin()返回指向第一个元素的指针,end()返回off-the-end指针.

vector<int> v;sort(begin(v), end(v));

4.以范围为基础的for循环。类似java的for

可以遍历的对象包括:数组;定义了begin()和end()方法,且返回该方法返回迭代器的类对象(STL 中所有容器)

std::vector<int> int_vec;int_vec.push_back(1);//如果要修改int_vec中的元素,将变量x声明为 auto& 即可for (auto &x: int_vec){    std::cout << x << endl;}
5.

6.final 防止类或者接口被继承。

class A final{};class B{  virtual void func() final;}

A B 都不能被继承。


7.必须显示虚函数重载。+ virtual  + override

8.强枚举类型 

在C++ 11中,引入了enum class来声明类型安全的枚举类型.还可以指定数据类型默认为int.

enum class EColor{red, black, green};enum class :unsigned int {};

9.模板别名 (解决typedef 定义模板别名的问题)

template< typename first, typename second, int third>class SomeType; template< typename second>using TypedefName = SomeType<OtherType, second, 5>;

一般类型别名:
using PFD = void (*)(double);


10.新的字符串编码。

C++ 11 支持三种Unicode编码方式:UTF-8,UTF-16,和UTF-32。除了上述char定义的变更。C++ 11还增加了两种新的字符类别:char16_t和char32_t,用于存储UTF-16和UTF-32的字符。

u8"this is utf8"  l类型 const char[]

u"this is utf16"  const char16_t[] 

U"this is utf32" const char32_t[]

11.包装引用。

包装引用类似于一般的引用。对于任意对象,我们可以通过模板类ref得到一个包装引用。cref 得到一个常引用。






0 0
原创粉丝点击