const

const 变量名开头大写,define 变量名全大写

1
2
3
4
5
6
7
8
9
10
11
12
13
int n = 10;
int m = 100;

const int *pt = &n; // a pointer to const int
*pt = 20; // invalid
pt = &m; // valid

int *const pt = &n; // a const pointer to int
*pt = 20; // valid
pt = &m; // invalid

int trouble = 75;
const int *const stick = &trouble; // a const pointer to const int

C++ 禁止将 const 的地址赋给非 const 指针

如果条件允许,应将指针形参声明为指向 const 的指针

将指针参数声明为指向常量数据的指针有 两条理由

  • 这样可以避免由于无意间修改数据而导致的编程错误;
  • 使用 const 使得函数能够处理 const 和非 const 实参,否则将只能接受非 const 数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const float g_earth = 9.80;
const float *pe = &g_earth; // VALID

const float g_moon = 1.63;
float *pm = &g_moon; // INVALID

int age = 39; // age++ is a valid operation
int *pd = &age; // *pd = 41 is a valid operation
const int *pt = pd; // *pt = 42 is an invalid operation

const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n

仅当只有一层间接关系(如指针指向基本数据类型)时,才可以将非 const 地址或指针赋给 const 指针

low-level const

const 修饰的是指针所指向的值

1
2
3
4
5
6
7
int a = 1;
const int *b = &a; // low-level const
// or
int const *b = &a;

*b = 2; // error
b = new int(2); // ok

high-level const

const 修饰的是指针本身

1
2
3
4
5
int a = 1;
int * const b = &a; // high-level const

*b = 2; // ok
b = new int(2); // error