在介绍常量指针和指针常量之前,先通过自己的理解画出这么一张图
指针和变量的实际内存关系是这个样子,指针有一片内存,存储地址值,而
变量本身也有一片内存,存储数据,指针通过自己保存的地址值操作并访问
变量的数据,而常量指针是对操作的约束,指针常量则是实现的对指针的本
身的约束。
也就是说,如果一个指针是常量指针,那么他本身是可以改变的,变量的
内容也是可以改变的,但是不能通过该指针来改变变量值;而指针常量则是
本身一旦确定了,则不可改变,但是可以通过操作来改变变量的值,变量本身
也可以改变自己的值。
再简单的说,常量指针就是对操作的约束,而指针常量就是对指针的约束。
可能很难以置信,我们通过代码实际运行来验证这个说法。
/*
定义一些常量
*/
#include <iostream>
using namespace std;
// 常量
const int const_temp = 404;
int const const_temp_b = 101;
// 变量
int temp = 404;
int temp_b = 101;
// 常量指针
const int * const_ptr = &const_temp;
int const * const_ptr_b = &const_temp;
// 指针常量
int * const ptr_const = &temp;
/*不被允许的指针常量定义
int * d const ptr_const_b = &temp;
*/
// 常量指针和指针常量
const int * const const_ptr_const = &const_temp;
// 普通指针
int * ptr;
/*
定义一些操作
*/
#include "MyConst.h"
// 关于常量指针
void ConstPtr()
{
// 自身可改变
cout << const_ptr << endl;
const_ptr = &const_temp_b;
cout << const_ptr << endl << endl;
// 可以指向变量
cout << * const_ptr << endl;
const_ptr = &temp;
cout << * const_ptr << endl << endl;
// 不可以可以通过常量指针修改变量值
// *const_ptr = 444;
// 可以通过其他方式修改该变量的值
cout << *const_ptr << endl;
temp = 101;
cout << *const_ptr << endl << endl;
}
// 关于指针常量
void PtrConst()
{
// 自身不可改变
// ptr_const = &temp_b;
// 可通过指针常量修改变量
cout << * ptr_const << endl;
*ptr_const = 202;
cout << * ptr_const << endl << endl;
// 可通过其他方式修改变量值
cout << * ptr_const << endl;
temp = 101;
cout << * ptr_const << endl << endl;
}
/*
主函数
*/
#include "MyConstOperate.h"
using namespace std;
/*
* 主函数
*/
int main()
{
// 常量指针
cout << "常量指针" << endl;
ConstPtr();
// 指针常量
cout << "指针常量" << endl;
PtrConst();
return 0;
}
在常量指针一部分,const_ptr 初始指向 const_temp,在 ConstPtr 里面第一块和第二块,分别将 const_ptr 指向另外的一个常量、变量,发现程序依旧可以正常运行,并且运行前后地址发生了改变,证明了常量指针自身是可以改变的;在二块内容中,已经将 const_ptr 指向了 temp 变量,所以在第四块中使用 temp 对自己进行修改,发现依旧可以正常运行,证明变量本身也是可以改变的,但是当使用const_ptr来修改变量的值的时候报错。
综上,常量指针是对操作的约束。
同理,在指针常量中也从 指针、操作、变量 这三个角度来验证,最后得出结论,指针常量是对指针的约束
最后,const int * const ptr 也是通过对指针和操作的约束来实现的,
具体的原理和常量指针和指针常量是一样的。
需要注意的是,常量指针由于本身是一个常量型的指针,所以变量方面不管
是不是常量,他都可以取当前值当作常量来用,但是如果是指针常量,由于他
本身是一个变量型的指针,所以变量方面必须得是一个变量,而不能用常量来
对这个指针进行赋值。