我所理解的C++ 02-3|类型别名、auto 和 decltype

本文最后更新于:2026年11月19日 下午

1. 类型别名

1
2
3
4
5
6
//使用typedef关键字定义类型别名
typedef double dType, *dTypePtr; //dType是double的同义词,dTypePtr是double*的同义词
typedef dType base, *basePtr; //base是double的同义词,basePtr是double*的同义词

//使用using关键字定义类型别名
using number = int; //number是int的同义词

阅读含有类型别名的代码时不要直接将类型别名替换成原来的类型来阅读,只能将类型别名对应的原来的类型从理解上当作一个整体来看

1
2
3
typedef char *pstring;
const pstring cstr = 0; //cstr类型是char * cosnt,是顶层const;不能理解成const char *这样的底层const
const pstring *ps; //ps类型是char *const *

2. auto关键字

使用auto关键字修饰变量可以让编译器通过初始值来推断出变量的类型。这也意味着使用auto关键字修饰变量时,必须初始化变量,例如auto i = 1;i的类型为int。

auto关键字可以在一条语句中定义多个变量,但是所有变量的初始值的基本类型必须一致。

1
2
auto i = 0, *p = &i;        //正确:基本类型都是int
auto sz = 0, pi = 3.15; //错误:sz的基本类型是int,pi的基本类型是double

auto与const

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int i = 1;
const int ci = i;
const int &cr = ci;

//编译器推断出的类型不一定和初始值的类型一致,编译器会适当改变推断的类型使其更符合初始化规则
auto b = ci; //类型为int,忽略ci的顶层const
auto c = cr; //类型为int,cr是ci的一个别名,忽略ci的顶层const

auto d = &i; //类型为int*
auto e = &ci; //类型为const int *,保留底层const
auto *p2 = &ci; //类型为const int *,保留底层const

const auto f = ci; //类型为const int

auto &g = ci; //类型为const int &
auto &h = 42; //错误
const auto &j = 42; //类型为const int &

3. decltype关键字

使用decltype关键字可以让编译器分析并返回表达式运算结果的数值类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int i = 42;
const int ci = i;
int &r = i;
const int &cj = ci;

//内容为变量时
decltype(i) o = 0; //int
decltype(ci) x = 0; //类型为const int
decltype(r) m = 0; //类型为int &
decltype(cj) y = x; //类型为const int &
decltype(cj) z; //类型为const int &,但没有初始化,所以报错

//内容为表达式时
int *p = &i;
decltype(r + 0) b; //类型为int
decltype(*p) c; //类型为int &,但没有初始化,所以报错
decltype((i)) d; //类型为int &,但没有初始化,所以报错
// decltype((<变量>))得到的类型永远都是引用
decltype(i=x) e; //类型为int &,但没有初始化,所以报错

我所理解的C++ 02-3|类型别名、auto 和 decltype
https://roudersky.com/posts/5f91a4fb.html
作者
Rouder
发布于
2022年3月19日
许可协议