const定义变量后,该变量就没有了写权限,只有读权限
1.const用于定义变量时,要进行初始化
例如: const int a = 10; //合法 const int a; //非法
2.数据类型对于const而言是透明的
例如: const int a = 10; 等价于 int const a = 10; const int* p1 = &a; 等价于 int const* p1 = &a; 但是这里要注意 const int* p1 = &a; 不等价于 int* const p1 = &a;
const int* p1 = &a; 指const修饰的是 *p1,即 *p1不可以被修改,内容是只读的;但是 p1 可以修改,可以指向其它的地址空间。
int* const p1 = &a; 指const修饰的是 p1,即 p1 不可以被修改,不能指向其它地址空间,但是 *p1 可以修改,内容可读可写。
如下代码给出了二者之间的使用区别:
#include <iostream> int main() { int i = 10; int j = 20; int const* p2 = &i; int* const p3 = &j; p2 = &j; //正确,因为const是对*p2进行限制的,不影响p2 *p3 = 20; //正确,因为const是对p3进行限制的,不影响*p3 //*p2 = 30; //错误,因为*p2已经被const修饰了,不能再次修改 //p3 = &j; //错误,因为p3已经被const修饰了,不能再次修改 return 0; }3.权限只能同等传递或者缩小传递 简单的一句话:非const可以调用const,const不可以调用非const
当const修饰函数返回值时,该返回值不能被改变
在上面的Date类中,我们为了防止在 operator= 函数中对象 d 修改私有成员变量,则可以加上const限定符。 但是在 Print 函数中如何给 this指针加上const限定符? 因为C++中函数形参 this指针是隐含的,不允许显示的写出来,所以规定 const 写在成员函数的后面。
void Print()const { cout << _year << "-" << _month << "-" << _day << endl; }