半小时掌握C++常量指针vs指针常量

112 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

常量指针

常量指针(pointer to const)

常量指针:如果在定义指针变量的时候,数据类型前用const修饰,被定义的指针变量就是指向常量的指针变量,指向常量的指针变量称为常量指针

const char *p 或 char const *p //给*p加保护罩,所以*p对应的对象不能改变
#include <iostream>
using namespace std;
​
​
int main(int argc, char **argv)
{
    char mystr[] = "this is an apple";
    char mystr2[] = "this is a dog";
    const char *p1 = mystr;
    cout<<p1<<endl;
    //*p1 = 'H';//错误,p1必须是可修改的左值 
    char const *p2 = mystr;
    //*p2 = 'H';//错误 ,p2必须是可修改的左值 
    p1 = mystr2;//可以修改 
    cout<<p1<<endl;
    return 0;
}
/*
this is an apple
this is a dog
*/

p指向的内容不能通过p来修改

指针常量

指针常量(constant pointer)

顾名思义它就是一个常量,但是是指针修饰的。

char* const p; 

给p加保护罩,所以p对应的对象不能改变

需要有初始值

不能修改p

可以修改*p

#include <iostream>
using namespace std;
​
​
int main(int argc, char **argv)
{
    char mystr[] = "this is an apple";
    char mystr2[] = "this is a dog";
    char* const p1 = mystr;
    cout<<p1<<endl;
    //char* const p1; //错误,常量p1需要初始化
    //p1 = mystr2;//错误,不能修改p1的值 
    *p1 = 'H'; //可以修改*p1的值 
    cout<<p1<<endl;
    
​
    return 0;
}
/*
this is an apple
Hhis is an apple
*/

指向常量的指针常量

const char* const b

需要有初始值

不能修改p

不能修改*p

#include <iostream>
using namespace std;
​
​
int main(int argc, char **argv)
{
    char mystr[] = "this is an apple";
    char mystr2[] = "this is a dog";
    const char* const p1 = mystr;
    //char* const p1; //错误,常量p1需要初始化
    //p1 = mystr2;//错误,不能修改p1的值 
    //*p1 = 'H'; //错误,不能修改*p1的值 
    cout<<p1<<endl;
    
​
    return 0;
}

思考

int * const p=&a;这个const修饰的是p,所以p不可以指向别的内存区域;

const int *p = &a;这个const修饰的是 int *,即指向的那个内存区域,故使用该指针是改变不了那个内存区域的内容的,但是那个内存区域本身是可以改变的;

另一种方式

const修饰的都是前面一个,int const p修饰的是int,说明p指向的int型变量是常量,而int * const p修饰的关键是,也就是p指针本身应该是常量指针,至于平常写const int *p其实就是int const *p只是提到前面看着比较舒服所以经常会这么写。

总结

当使用带有指针的const时,有两种选择: const修饰指针正在指向的对象, const修饰在指针里存储的地址” 只需要遵循指针的定义技巧“从指针标识符开始,由里到外地读,const修饰最靠近它的那个”就能帮助理解