基本原则:
- 从右向左读。
- 指向常量的指针(pointe to const):const在 * 左边,则声明指针指向的对象是常量,但指针指向的地址可以变。
- 常量指针(const pointer):const在 * 右边,则声明指针是常量(常指针,指针常量)。
- 指向常量的指针:const在 * 左边,表明指向的对象是常量:
const double value = 20.0;
const double *ptr1 = &value;
double const *ptr2 = &value;
std::cout << "ptr1: " << ptr1 << ", *ptr1: " << *ptr1 << std::endl;
std::cout << "ptr2: " << ptr2 << ", *ptr2: " << *ptr2 << std::endl;
double new_value = 1.0;
ptr1 = &new_value;
ptr2 = &new_value;
std::cout << "ptr1: " << ptr1 << ", *ptr1: " << *ptr1 << std::endl;
std::cout << "ptr2: " << ptr2 << ", *ptr2: " << *ptr2 << std::endl;
输出:
ptr1: 0x7ffc844d8754, *ptr1: 20
ptr2: 0x7ffc844d8754, *ptr2: 20
ptr1: 0x7ffc844d8758, *ptr1: 1
ptr2: 0x7ffc844d8758, *ptr2: 1
ptr: 0x7ffc844d8754, *ptr: 20
ptr2: 0x7ffc844d8754, *ptr2: 20
ptr: 0x7ffc844d8758, *ptr: 1
ptr2: 0x7ffc844d8758, *ptr2: 1
- 常量指针:const 在 * 后修饰指针则表明此指针是常量,地址不可变,值可变。
int val = 10;
const int cval = 100;
int *const cptr = &val;
std::cout << "val: " << val << ", cval: " << cval << ", cptr:" << cptr << ", cptr value:" << *cptr << std::endl;
*cptr = 11;
std::cout << "val: " << val << ", cval: " << cval << ", cptr:" << cptr << ", cptr value:" << *cptr << std::endl;
输出
val: 10, cval: 100, cptr:0x7ffdcb88a668, cptr value:10
val: 11, cval: 100, cptr:0x7ffdcb88a668, cptr value:11
- 指向常量的常指针,指针地址不可变,指向的值不可变。
const float cval = 20.0;
const float *const fcptrc = &cval;
类中的const相关
- const 成员函数规范: <类型说明符> <函数名> (<参数表>) const;
i.const成员函数内不得修改成员变量。
ii.const成员函数内不得调用非const成员函数。
iii.只有常成员函数才有资格操作常量或常对象,没有使用const关键字说明的成员函数不能用来操作常对象。