C++ const指针
const指针
基础:const是constant的缩写,意思是不变的。也就是说const修饰的变量,是不能被改变的。
指针定义 int *p,那么我们来看一下 const加入int *p有三个地方可以加,分别是const int *p,int const *p,int *const p。
1.const int *p 和 int const *p
我们可以类比 const int num=1; 和 int const num=1;,两者是等价的。所以const int *p 和 int const *p是等价的。
接下来我们看,const int *p 的类型是什么?首先他是一个常量const,然后是一个指针。因此p就是常量指针。
常量指针:指针的指向可以修改,指向的值不可以修改。常量指针,首先得是常量,就是指向的值必须为常量,但是地址可以修改。
#include<iostream> using namespace std; // 将const关键字用于指针 int main(){ // 指针指向的数据为常量,不能修改,但可以修改指针包含的地址 int num=10; // 常量指针,指向的值必须为常量。 const int * p = & num; // p cout << "P: " << p << endl; // num 的地址 cout << "&num: " << &num << endl; // 修改指针包含的地址,常量一样,重新定义一个num2=10 int num2=10; // 修改指针包含的地址 p = & num2; // p &num &num2 可以看到常量值不变,指针包含的地址改变 cout << "P: " << p << endl; cout << "&num" << &num << endl; cout << "&num2" << &num2 << endl; return 0; }
如图所示,指针指向可以修改,但是指针的值不可以修改。
2.int *const p,首先是一个整型指针int *,然后一个const 常量,因此是指针常量。
指针常量:指针的指向不可以修改,指针指向的内存值可以修改。可以看到先有指针int *,然后有const 常量修饰的p,因此p的值是不可以修改的(指向的内存地址)。
#include<iostream> using namespace std; // 将const关键字用于指针 int main(){ // 指针包含的地址是常量,不能修改,可修改指针指向的数据 int *const p = new int; * p=10; cout << *p << endl; cout << p << endl; // 修改指针指向的数据,p存储的地址没有改变 * p =20; cout << *p << endl; cout << p << endl; return 0; }
箭头是指针指向的内存值,不可以修改,但是指向的内存地址中的数据可以修改。
3.const int *const p;指向常量的常指针,很好理解,都不能修改,指针的指向不可以修改,指向的值也不可以修改。
#include<iostream> using namespace std; // 将const关键字用于指针 int main(){ // 指针指向的数据和地址都为常量,不能修改 int num=10; const int * const p = & num; cout << p << endl; cout << *p << endl; return 0; }