Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
MachineLP committed Sep 30, 2019
1 parent fa8071f commit 1d70304
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions 01-programming_language/03-c++/01-auto类型说明符.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

**auto类型说明符**:能让编译器替我们去分析表达式所属的类型。所以auto定义的变量必须有初始值。
使用auto也能在一条语句中声明多个变量。因为一条声明语句只能有一个基本数据类型,所以该语句中所有的变量的初始基本数据类型必须一样:

```
auto i= 0,*p = &i; // 正确:i是整数、p是整形指针。
auto sz = 0, pi = 3.14; //错误:sz和pi的类型不一致
```
**复合类型、常量和auto**

```
int i=0, &r = i;
auto a = r; //a是一个整数(r是i的别名,而i是一个整数)
```

其次,auto一般会忽略掉顶层const,同时底层const则会保留下来,比如初始值是一个指向常量的指针时:

```
const int ci = i, &cr = ci;
auto b = ci; // b是一个整数(ci的顶层特性被忽略掉了)
auto c = cr; // c是一个整数(cr是ci的别名,ci本身是一个顶层const)
auto d = &i; // d是一个整型指针(整数的地址就是指向整数的指针)
auto e = &ci; // e是一个指向整数常量的指针(对常量对象取地址是一个底层const)
```
如果希望推断出的auto类型是一个顶层const,需要明确指出:

```
const auto f = ci; // ci推演类型是int,f是const int;
还可以将引用类型设为auto,此时原来的初始值仍然适用:
auto &g = ci; // g是一个整型常量引用,绑定到ci
auto &h = 42; // 错误:不能为非常量引用绑定字面值
const auto &j = 42; // 正确:可以为常量引用绑定字面值

0 comments on commit 1d70304

Please sign in to comment.