const pointer 与 pointer to const variable 的区别

本文详细解释了C++中三种不同类型的指针:普通指针、常量指针和指向常量的指针的区别,通过实例演示它们如何影响变量的赋值和修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果能分清  T const * prt ;

                 const T * prt;

                 T * const prt;

三者区别, 就可以不用往下看了

 

A const pointer essentially means you can’t change the pointer variable itself, but you can change the value it points to.

const pointer(常量指针) 表示这个指针是指向一个固定的地址,  不能一会指向这,一会指向那;

 

A pointer to const means you can change the pointer but not what it points to;

 

a pointer to const (指向常量的指针)表示指针指向的 变量是一个常量, 不能改变这个常量的针,  但却可以改变指针的值, 让它指向别的地方。

 

 

 

int a = 100;
int * const prt = &a;// 表示prt指针是 常量指针, 不能改它的值

//prt++; <- won't compile ,若想改变它, 编译的时候会报错

*prt = 250; //但是可以改变它指向的变量的值



 

int a = 100

int const * prt  = &a; //指向常量的指针,pointer to const variable

//也可以这么写

const int *prt = &a;  //指向常量的指针,pointer to const variable

//这两种写法区别不大, const int ,  int const 不区分前后, 与java中
//public static ,  static public 一样,不分前后

*prt = 200; //不能这么写,编译出错, 常量的值怎么可以改变呢

prt ++; //没关系, 指针的值可以随便改;

 

reference:

http://blog.voidnish.com/?p=37

http://www.allinterview.com/showanswers/36962.html

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值