typedef和*的混合应用

今天看大了一个而有趣的语法,typedef int,INTR,*PINTR;
我很费解,PINTR到底是个什么类型?如果它是int*,星号不应该紧跟写在int的后面吗?于是做了几个小小的测验。

typedef int NIU,*LEI;
int a;
NIU num=a;//正确
NIU num=&a;//错误,int*无法转换为int类型
LEI num=a;//错误,int无法转换为int*类型
LEI num=&a;//正确

看来为int指针起别名的方式是将*紧贴别名名称,那如果我按如下方式定义呢?

typedef int* NIU,LEI;
int a;
NIU num=a;//错误,int无法转换为int*类型
NIU num=&a;//正确
LEI num=a;//正确
LEI num=&a;//错误,int*无法转换为int类型

结果又有点不直观,NIU是int*类型的,LEI是int类型的,看来*只能起到一次作用,离谁最近谁生效。
typedef真的是和人的直观感觉不同,这样下去起步太容易出错了?不如用decltype,则能达到与人直觉相同的结果:

int* etc=new int(1);
typedef decltype(etc) NIU,LEI;
int a;
NIU num=a;//错误,int无法转换为int*类型
NIU num=&a;//正确
LEI num=a;//错误,int无法转换为int*类型
LEI num=&a;//正确

猜你喜欢

转载自blog.csdn.net/qq_36946274/article/details/80990321
今日推荐