复杂类型的处理-typedef、using、auto、decltype

复杂类型的处理

1.类型别名
自定义类型的同义词,使得复杂的类型名字变得简单明了、易于理解和使用
1.1 typedef

typedef char* pstring//定义pstring与char*同类型

1.2 using-别名声明
using pstring=char*//定义pstring与char*同类

注意:如果类型别名指代复合类型或常量,用于声明中可能出错

    typedef char* pstring;
	const pstring cstr = 0;//cstr是指向char的常量指针
	const char * cstr=0//不等同于上,*成为声明符的部分,此时cstr是指向const char的指针
	

2.auto 类型说明符
通过初始值自动获得变量的类型

  • auto忽略顶层const,保留底层const;
  • 一条语句定义多个变量初始值必须同类型,但注意&*只是类型修饰,从属与某声明符。
int i = 0, & r = i;
	auto a = r;
	const int ci = i, & cr = ci;//const int 
	auto b = ci;//int,auto忽略顶层const 
	auto c = cr;//int,忽略顶层const
	auto d = &i;//int*
	auto e = &ci;//int * const,保留底层const
	const auto f = ci;//const int ,顶层const需明确指出
	auto & g = ci;//引用g绑定ci
	auto & h = 42;//错误 初始化,非const不能引用字面值
	const auto& j = 42;//正确初始化,j为const引用
	auto k = ci, & l = i;//同int和int & 
	auto& m = ci, * p = &ci;//同const int &和 const int *
	auto& n = i, * p2 = &ci;//错误int & 和const *  不同类型
   const int i = 42;
	auto j = i;//int
	const auto& k = i;//const int &
	auto* p = &i;//const int *
	const auto j2 = i, & k2 = i;//j2 const int ,k2  const int &

3.decltype类型指示符
从表达式类型推断出定义的变量的类型,但不用改表达式的值初始化变量。
其作用:选择并返回操作数的数据类型,但并不实际计算

decltype(f()) sum = x;//f的返回值作为sun的类型

如果f是一个变量,则返回变量的类型(包括顶层const和引用)。

    const int ci = 0, & cj = ci;
	decltype(ci) x = 0;//const int 
	decltype(cj) y = x;//const int &
	decltype(cj) z;//const int &,这里引用但未初始化,错误

其中decltype(ci)相当于const intdecltype(cj)相当于const int &

*注:*f是表达式,如果内容是解引用操作,返回引用类型。

`int i=1,*p=&i;decltype(*p) c;//错误,c为int &,必须初始化

注:如果f为变量加括号后,返回引用类型。

decltype((i)) d;//错误,d为int &,必须初始化

autodecltype的差别:

  1. 顶层const
  2. 引用问题
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值