c/c++语言开发共享C++ 11

恢复内容开始 C++11 新特性 借鉴于 https://www.cnblogs.com/feng-sc/p/5710724.html C++ 2011/2014 统称 C++2.0 1.auto关键字 auto这个关键字,是一个自动检测类型的关键字,当类型很复杂时,无法确定变量/参数类型时,可以使 …

—恢复内容开始—

c++11 新特性 借鉴于 https://www.cnblogs.com/feng-sc/p/5710724.html

c++  2011/2014 统称 c++2.0

1.auto关键字

  auto这个关键字,是一个自动检测类型的关键字,当类型很复杂时,无法确定变量/参数类型时,可以使用该auto关键字

2.null 和 nullptr 区别

  就是指在c++2.0之前定义的null 的定义是  #define null 0   这是他的原型,实际使用的时候实际时传入的确是null,而类型缺是指针

而nullptr的引入会减少null调用错误 

class test { public:     void testwork(int index)     {         std::cout << "testwork 1" << std::endl;     }     void testwork(int * index)     {         std::cout << "testwork 2" << std::endl;     } };  int main() {     test test;     test.testwork(null);     test.testwork(nullptr); } 

3. for 循环

c++ 11 中增加了auto,还加强了for循环,并还引入了for each语句

第一种for:

int main() {     int numbers[] = { 1,2,3,4,5 };     std::cout << "numbers:" << std::endl;     for (auto number : numbers)     {         std::cout << number << std::endl;     } }

第二种for each:

#include <array> #include <iostream> #define __text      int main() { #ifdef __text //c++11 code std::array<int, 4> arraydemo = { 1,2,3,4 }; std::cout << "arraydemo:" << std::endl; for each(auto itor in arraydemo) {     std::cout << itor << std::endl; }  int arraydemosize = sizeof(arraydemo); std::cout << "arraydemo size:" << arraydemosize << std::endl; #endif  #ifndef _array__  int nums[] = {1,2,3,4,5,6}; for each(auto num in nums) {     std::cout << num << std::endl; } #endif getchar(); return 0; }

4.stl 容器补充

5.thread —引入boost::thread库 (头文件<thread>)

  ——>thread:

  ——>atomic 类型:

  ——>condition_variable:

6.std::function std::bind (头文件functional)

  由boost库引用而来,可以与lambda表达式混合使用

  

     void add(std::function<int(int, int)> fun, int a, int b)         {                 int sum = fun(a, b);                 std::cout << "sum:" << sum << std::endl;         }     function<int(int,int)>

  function是对函数指针的一个封装 typedef  类型 (*funciton)(参数表) bind(函数指针,对象指针,参数占位表)

7.lambda表达式

int main() {     auto add= [](int a, int b)->int{         return a + b;     };     int ret = add(1,2);     std::cout << "ret:" << ret << std::endl;     return 0; }

解释:

  第3至5行为lamda表达式的定义部分

  []:中括号用于控制main函数与内,lamda表达式之前的变量在lamda表达式中的访问形式;

  (int a,int b):为函数的形参

  ->int:lamda表达式函数的返回值定义

  {}:大括号内为lamda表达式的函数体。

8.auto_ptr、shared_ptr、weak_ptr(头文件<memory>)

  ——>shared_ptr std::shared_ptr包装了new操作符动态分别的内存,可以自由拷贝复制,基本上是使用最多的一个智能指针类型。

  使用 : std::shared_ptr<test> p1 = std::make_shared<test>();

—恢复内容结束—

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606340.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐