示例代码
class test {
public:
int get_a () const {
return a;
}
int get_b () {
return b;
}
private:
int a;
int b;
};
int main () {
const test test_obj_1 = test(); // 常量对象
test test_obj_2 = test(); // 非常量对象
test_obj_1.get_a(); // 正确
// test_obj_1.get_b(); // 编译错误
test_obj_2.get_a(); // 正确
test_obj_2.get_b(); // 正确
return 0;
}
成员函数 const 关键字的作用
成员函数添加 const 关键字作用之一为:修改隐式 this 指针的类型。
默认情况下,this 的的类型是指向类类型非常量版本的常量指针(const pointer)(而非 pointer to const)。根据初始化规则,不能将 this 绑定到一个常量对象上。
如示例代码所示,不能在常量对象上调用普通的成员函数(非 const,无法传入隐式 this 指针),需要将其声明为指向常量的指针。由于 this 为隐式参数且不会出现在参数列表中,C++ 提供声明 this 为指向常量的指针的方法为在成员函数的参数列表之后添加 const 关键字。
使用 const 关键字的成员函数称为常量成员函数。
补充
- 常量指针(const pointer)
初始化完成后,指针指向无法更改;符号 * 在 const 关键字之前,用以说明指针为常量;int test_val = 0; int * const cp = &test_val;
- 指向常量的指针(pointer to const)
不能用于改变其所指对象的值;符号 * 在 const 关键字之后;const double pi = 3.14; double *ptr = π // 错误:ptr是一个普通指针 const double *cptr = π // 正确:cptr为指向常量的指针