auto和decltype

auto

auto:编译器通过初始值推断变量类型–auto定义的变量必须有初始值

//auto在同一语句中可以声明多个对象,但必须为同一类型
auto i = 0, *p = &i // 正确,均为int
auto sz = 0, tz = 3.1 // 错误

//auto使用引用作为初始值时,使用**引用对象的类型**作为auto类型
int &a = i;
auto x = &a; // x类型为int

//auto一般会忽略顶层const
const int a = 1, &ar = a; // 顶层const
int i = 0;
const int ai = i; // 顶层const
auto b = a; //int b,丢掉了const
auto c = &ar; // int c,丢掉了const
auto d = &a; // int *d
auto e = &ai; // int *e
auto &f = a; // int &f

//手动加const
const auto cb = a; // const int cb
const auto &cf = a; // const int &cf

decltype

从表达式类型推断变量类型

decltype(f()) sum = x // sum的类型为函数f()返回值的类型

//会保留顶层const
const int ci = 0, &cj = ci;
decltype(ci) x = 0; // const int x = 0
decltype(cj) y = x; // const int &y = x
//引用只作为指向的对象的同义词出现,只有在decltype处例外

// decltype的结果可以是引用类型
int i = 42, *p = &i, &r = i;
decltype(r + 0) b; // int b
decltype(*p) c = i; // int &c = i

// decltype中的表达式如果加上括号,一定是一个引用类型
decltype((i))  d = i; // int &d = i

decltype((variable)) 双层括号,得到的一定是一个引用

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值