File tree Expand file tree Collapse file tree 2 files changed +87
-0
lines changed
source/Language Core/Chapter-2 Expand file tree Collapse file tree 2 files changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ # 类型推导
2+
3+ 类型推导是一种能让编译器根据初始化或表达式推断变量类型的机制
4+
5+ ## 自动类型推导
6+
7+ 自 C++ 11 开始新增 ** ` auto ` ** 关键字,主要是用来解决变量在显式指定数据类型可能导致的复杂或冗长,` auto ` 的作用是根据初始化表达式自动推导变量的类型
8+
9+ 使用语法:
10+
11+ ``` CPP
12+ auto 变量名称 {值};
13+ ```
14+
15+ 代码演示:
16+
17+ ```CPP
18+ auto x = 10; // int
19+ auto y = 3.14; // double
20+ auto z = 'A'; // char
21+ ```
22+
23+ ``` {attention}
24+
25+ auto 必须设定一个初始值,因为编译器需要通过初始化表达式才能推导出类型
26+
27+ ```CPP
28+ auto x; // 编译错误,auto 必须有初始值
29+ ```
30+
31+ auto 在推导时默认会丢弃 const 属性,如果需要保留常量属性,需要显式添加 const。
32+
33+ ``` CPP
34+ // 常量代码演示
35+ const int a{10};
36+
37+ auto b{a}; // b 的类型是 int(const 被丢弃)
38+ const auto c{a}; // c 的类型是 const int
39+ ```
40+
41+ 优点:
42+
43+ - 减少代码冗余
44+ - 提高代码可维护性
45+ - 避免手写类型错误
46+
47+ 缺点:
48+
49+ - 可读性下降(类型不直观)
50+ - 容易丢失 const 和引用
51+ - 某些情况下可能导致隐式类型错误
52+
53+ ## 表达式类型推导
54+
55+ 表达式类型推导 `decltype` 同样是 C++ 11 引入的关键字,它用于根据表达式本身推导类型,并完整保留类型信息
56+
57+ 使用语法:
58+
59+ ```CPP
60+ decltype(表达式) 变量名称;
61+ ```
62+
63+ 代码演示:
64+
65+ ``` CPP
66+ int x{10};
67+
68+ decltype (x) y{20}; // y 的类型是 int
69+ ```
70+
71+ 与 auto 不同的是 decltype 会保留 const 属性。
72+
73+ ```CPP
74+ const int a{10};
75+
76+ decltype(a) b = 10; // b 的类型是 const int
77+ ```
78+
79+ decltype 会完整保留 const 属性,如果赋值不符合 const 要求将导致编译错误。
80+
81+ ## 使用建议
82+
83+ - 类型复杂时优先使用 auto
84+ - 类型明显时可直接使用具体类型
85+ - 涉及引用或 const 时使用 decltype
86+ - 避免在简单场景中滥用 decltype
Original file line number Diff line number Diff line change @@ -7,4 +7,5 @@ Section-01
77Section-02
88Section-03
99Section-04
10+ Section-05
1011```
You can’t perform that action at this time.
0 commit comments