0%

C++ Primer学习笔记(三)

别名(Type Aliases)

  • 写法一
1
2
3
4
5
typedef double wages; // wages is a synonym for double
typedef wages base, *p; // base is a synonym for double, p for double*

wages i = 1.0;
p val = &i;
  • 写法二
1
using SI = int; // SI is a synonym for int

C++11支持

1
2
3
typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char
const pstring *ps; // ps is a pointer to a constant pointer to char

auto类型

编译器会自动通过初试值来判断auto对象的类型

1
2
autoi=0,*p=&i; //ok: i is int and p isapointerto 
int auto sz = 0, pi = 3.14; // error: inconsistent types for sz and pi
  • auto会自动忽略top-level const,保留low-level const

    top-level const即自身为常量

    low-level const即自身可以修改,但是所指向(引用)的地址储存值为常量

    1
    2
    3
    4
    const int ci = i, &cr = ci;
    auto b = ci; // b is an int (top-level const in ci is dropped)
    auto c = cr; // c is an int (cr is an alias for ci whose const is top-level) autod=&i; // d isan int*(& ofan int objectis int*)
    auto e = &ci; // e is const int*(& of a const object is low-level const)
  • 设置为top-level const

    1
    const auto f = ci; // deduced type of ci is int; f has type const int