美文网首页
2021-04-18

2021-04-18

作者: 瑜明青云 | 来源:发表于2021-04-18 19:19 被阅读0次

C++11新特性

  • auto

    • 可以从初始化表达式中推断出变量的类型,大大简化编程工作
    • 属于编译器特性,不影响最终的机器码质量,不影响运行效率
      int a = 10;
      int b = 20;
    
      auto p = [a] () mutable {
          a++;
          cout << "lambda - " << a << endl;
      };
      p();
    
    
  • decltype

    • 可以获取变量的类型
  • nullptr

    • 可以解决NULL的二义性问题

Lambda表达式

  • Lambda表达式
    • 有点类似于JavaScript中的闭包、iOS中的Block,本质就是函数
    • 完整结构: [capture list] (params list) mutable exception-> return type { function body }
      • ✓capture list:捕获外部变量列表
      • ✓params list:形参列表,不能使用默认参数,不能省略参数名
      • ✓ mutable:用来说用是否可以修改捕获的变量
      • ✓ exception:异常设定
      • ✓return type:返回值类型
      • ✓function body:函数体
    • 有时可以省略部分结构
    • ✓[capture list] (params list) -> return type {function body}
    • ✓[capture list] (params list) {function body}
    • ✓[capture list] {function body}
int (*p)(int, int) = [](int a, int b) -> int {
        return a + b;
    };

    cout << p(10, 20) << endl;

cout << [](int a, int b) -> int {
        return a + b;
    }(10, 20) << endl;

cout << [](int a, int b) {
        return a + b;
    }(10, 20) << endl;
// 默认情况是值捕获
    auto p = [=, &a] {
        cout << a << endl;
        cout << b << endl;
    };

    a = 11;
    b = 22;

    p();

int a = 10;
    int b = 20;

    auto p = [a] () mutable {
        a++;
        cout << "lambda - " << a << endl;
    };
    p();
mutable 相当于a有个临时变量

C++ 17

if (int a = 10;  a > 5) {

    }
    else if (int b = 20; b > 10) {

    }
    else if (2) {

    }
    else {

    }

相关文章

网友评论

      本文标题:2021-04-18

      本文链接:https://www.haomeiwen.com/subject/mwpvlltx.html