栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++笔记--auto

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++笔记--auto

         auto(自动,automatic)是存储类型标识符,表明变量"自动"具有本地范围,块范围的变量声明(如for循环体内的变量声明)默认为auto存储类型。 auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,类似的关键字还有decltype。举个例子:

    int a = 20;
    auto au_a = a;
    cout << typeid(au_a).name() << endl;

输出:int

分析: 这种用法就类似于JavaScript中的var关键字,auto的自动类型推断发生在编译期;

#include 
using namespace std;

int main() {
  auto greet = []() {
    cout << "Hello World!";
  };

  greet();

  return 0;
}

输出:

Hello World!

再看个栗子

#include
using namespace std;

int main() {
  auto operation = []  (int a, int b,  string op) -> double {
    if (op == "sum") {
      return a + b;
    }
    else {
      return (a + b) / 2.0;
    }
  };

  int num1 = 1;
  int num2 = 2;

  auto sum = operation(num1, num2, "sum"); 
  cout << "Sum = " << sum << endl;

  auto avg = operation(num1, num2, "avg"); 
  cout << "Average = " << avg;

  return 0;
}

输出:

Sum = 3
Average = 1.5

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号