C++学习日志19--变量的定义方法auto、declpyte


一、auto

#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
using std::cin;
auto max(int x, int y)
{
    return x > y ? x : y;

}
int main()
{
     //auto 变量必须在定义时初始化
    auto x = 3;
    auto y{ 42 };

    //定义在一个auto序列的变量必须始终推导成同一类型
    auto x1{ 1 }, x2{ 2 };

    //如果初始化表达式是引用或者const,泽去除引用或const语义
    int y1{ 42 }, & y2{ y1 };
    auto y3{ y2 };
    cout << typeid(y3).name() << endl;

    //如果auto关键字带上&号,则不去除引用或const语意
    auto& z1{ y2 };
    cout << typeid(z1).name() << endl;

    //初始化表达式为数组是,auto关键字推导类型为指针
    int p[3]{ 1,2,3 };
    auto p1 = p;
    cout << typeid(p1).name() << endl;

    //若表达式为数组且auto带上&,则推导类型为数组类型
    auto& p2{ p };
    cout << typeid(p2).name() << endl;

    //C++14中,auto可以作为函数的返回值类型和参数类型
    cout << max(x1, x2) << endl;

    cin.get();


    return 0;
}

在这里插入图片描述

auto可以自行推断并且给出变量的类型,C++中应尽可能使用auto去定义。

二、declpyte

#include <iostream>
#include <typeinfo>
using namespace std;
int fun1() { return 10; }
auto fun2() { return 'g'; } //C++14
int main()
{

    //Data type of x is same asreturn type of fun1()
    //and type of y is same as return type of fun2()
    decltype(fun1()) x;
    decltype(fun2()) y=fun2();
    cout << typeid(x).name() << endl;
    cout << typeid(y).name() << endl;
    cin.get();


    return 0;
}

在这里插入图片描述

decltype在编译时期推导一个表达式的类型,而不用初始化,其语法格式有点像sizeof。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@白圭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值