char * const p 和 char const * p 和const char * p区别

const char *p; //和char const *p  数据为常量
char * const p; //常量指针,p的值不可以修改 
char const * p;//指向常量的指针,指向的常量值不可以改 
 
总结:
(1) char* a这种形式:a为指针,可以改变其指向,其所指向的字符串为常量,不能修改其指向的内容。  
(2) char a[]这种形式,a为数组名,为常量,不能再指向其它字符串,但其指向的内容不是常量字符串,故可以改变。  
  
(1) const char* a 为指向常量的指针,所指内容为常量,不能修改,但可以改变其指向,这种形式还与char const * a等价。  
(2) char* const a 为指针常量,不能改变其指向,但可以修改其指向的内容。  
(3) const char* const a 为指向常量的常指针,即不能改变其指向,也不能改变其指向的内容  
 
 
把一个声明从右向左读:
char * const cp; //( * 读成 pointer to )    cp is a const pointer to char 
 
const char * p;  //p is a pointer to const char; 'p' isn't modifiable but the pointer is
 
char const * p; //同上因为C++里面没有const*的运算符,所以const只能属于前面的类型。 
 
///C++标准规定,const关键字放在类型或变量名之前等价的。
 
const int n=5;    //same as below
int const m=10;
 
const int *p;    //same as below  const (int) * p
int const *q;    // (int) const *p
 
 
 
 
Read it backwards...
 
int* - pointer to int
int const * - pointer to const int
int * const - const pointer to int
int const * const - const pointer to const int
Now the first const can be on either side of the type so:
 
const int * == int const *
const int * const == int const * const
If you want to go really crazy you can do things like this:
 
int ** - pointer to pointer to int
int ** const - a const pointer to a pointer to an int
int * const * - a pointer to a const pointer to an int
int const ** - a pointer to a pointer to a const int
int * const * const - a const pointer to a const pointer to an int
...
And to make sure we are clear on the meaning of const
 
const int* foo;
int *const bar; //note, you actually need to set the pointer here because you can't change it later ;)
 
foo is a variable pointer to a constant int. This lets you change what you point to but not the value that you point to. Most often this is seen with cstrings where you have a pointer to a const char. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed.
 
bar is a const or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow null pointers.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值