引入类型别名的两种方式
typedef int MyInt;using MyInt = int;
使用using引入类型别名的方式更好
typedef char MyCharArr[4];using MyCharArr char[4];
类型别名与指针、引用的关系
- 注意类型别名不是简单的替换:
第一段代码完全没问题,是可以运行的
#include <iostream>int main(){int x = 4;const int* ptr = &x;int y = 5;ptr = &y; // 可以改变指针ptr的指向//*ptr = 7; 这一行是会报错的,注意第6行}
第二段代码出现了问题
#include <iostream>using IntPtr = int*;int main(){int x = 4;const IntPtr ptr = &x;int y = 5;ptr = &y;}

注意 “variable ‘ptr’ declared const here”,显然和我们的预期不符合;
替换后的效果反而和下面的代码一样:
#include <iostream>//using IntPtr = int*;int main(){int x = 4;int* const ptr = &x;int y = 5;ptr = &y;}

我们可以进一步验证:
#include <iostream>using IntPtr = int*;int main(){int x = 4;const IntPtr ptr = &x;*ptr = 7;std::cout << x;}

因此,我们应该将指针类型别名视为一个整体,在此基础上引入常量表示指针为常量的类型
- 不能通过类型别名构造引用的引用
下面这段代码:
#include <iostream>#include <type_traits>using RefInt = int&;using RefRefInt = RefInt&;int main(){std::cout << std::is_same_v<RefInt,RefRefInt> << std::endl;}

可见 int& 和 RefInt 、RefRefInt是同一种类型
