指向指针的指针
1 | int ival = 1024; |
指向指针的引用
1 | int i = 42; |
如何理解
int *&r = p;
?从右往左看,最靠近
r
的是&
,说明r
是一个引用,然后是*
,说明r
指向指针,最后是int
,说明r是一个指向int类型指针的引用。
Exercises Section 2.3.3
Exercise 2.25: Determine the types and values of each of the following variables.(a) int* ip, &r = ip;
(b) int i, *ip = 0;
(c) int* ip, ip2;
(a) ip:int类型的指针,r:指向int类型指针的引用
(b) i:int类型的变量,ip:int类型的指针
(c)ip:int类型的指针,ip2:int类型的变量
常量限定符(const)
- const修饰的对象不可修改
1 | const int bufSize = 512; // input buffer size |
- const修饰的对象必须初始化
1 | const int i = get_size(); // ok: initialized at run time |
- 在多个文件中使用const修饰的对象
1 | // file_1.cc defines and initializes a const that is accessible to other files |
Exercises Section 2.4
Exercise 2.26: Which of the following are legal? For those that are illegal,explain why.
(a) const int buf;
(b) int cnt = 0;
(c) const int sz = cnt;
(d) ++cnt; ++sz;
(a):❌ (d):++cnt;(✅)++sz;(❌)
常量引用
1 | const int ci = 1024; |
- 常量引用不可修改值
- 非常量引用不可指向常量对象
1 | int i = 42; |
常量引用可以指向 非常量对象、字面量、通用表达式
1 | double dval = 3.14; |
- 常量引用会自动强制类型转化
1 | const int temp = dval; // create a temporary const int from the double |
常量指针(pointer to const)
指向常量的指针,指针地址可以修改,但地址存放的值不可以修改
1 | const double pi = 3.14; // pi is const; its value may not be changed |
- 指向常量的指针地址存放的值不可修改
1 | double dval = 3.14; // dval is a double; its value can be changed |
- 指向常量的指针可以指向非常量对象
指针常量(const Pointers)
1 | int errNumb = 0; |
从右往左看:
curErr
被const
修饰,不可修改
1 | *pip = 2.72; // error: pip is a pointer to const |
Exercises Section 2.4.2
Exercise 2.27: Which of the following initializations are legal? Explain why.(a) int i = -1, &r = 0;
(b) int const p2 = &i2;
(c) const int i = -1, &r = 0;
(d) const int *const p3 = &i2;
*(e)** const int *p1 = &i2;
(f) const int &const r2;
(g) const int i2 = i, &r = i;(a)❌ 引用必须指向一个对象
(f) ❌常量必须初始化
Exercise 2.28: Explain the following definitions. Identify any that are illegal.
(a) int i, *const cp;
(b) int *p1, *const p2;(c) const int ic, &r = ic;
(d) const int *const p3;
(e) const int *p;
原因:常量初始化没有赋值
常量表达式
常量表达式是指能够在编译时确定值
1 | const int max_files = 20; // max_files is a constant expression |
尽管sz是一个常量,但是它的值只有在运行时才能确定,因此sz不是一个常量表达式
constexpr
1 | constexpr int mf = 20; // 20 is a constant expression |
constexpr避免了出现上述
sz
的情况
1 | const int *p = nullptr; // p is a pointer to a const int |
constexpr是top-level const,即指针本身是常量(low-level const是指针指向常量对象)
1 | constexpr int *np = nullptr; // np is a constant pointer to int that is null |