常量指针与指针常量

 
1 常量指针!如 int b, c; int * const a = &b;
表示 a 是一个常量指针它指向变量 b 的内存。但是因为是常量指针所以不能再用 a 指向其他变量,如 a = &c; 错误!可以修改指向内存的值,如 :*a = 20; BTW 常量指针声明的时候必须向我那样赋初值。

2
指向常量的指针!如 int b, c; int const *a; a = &b; a = &c;
都可以,唯独它指向的内存不能被修改。如: *a=20; 这是违法的!错误!

这就是主要区别!

BTW
还有一个记住他们不同形式的技巧!看 const 关键字,他后面的不可修改,如 int * const a = &b; 后面是 a, 则说明 a 不能修改!
int const * a = &b;
后面是 *a 则说明 *a 不可被修改!

在好多书上或 MSDN 是经常用 const int a=5;
int b=6;
const int *p=&b;
其实 const int* int const* 一样,就是常指针 也就是它所指向的数据(在这是 int )是常量,它自己的数据类型是 const int*
还有 const int *p=&b; 是可以的 虽然 b 不是常量。
但是 const int a=6;
int *p=&a;
会报错,因为它消除了 a const 属性 (这一点要特别注意,因为 const 定义以后,常量不能取地址?)
**********************************************

*******
我们可以总结一下 ********
1.
对于常量(符号常量)和常指针、常引用常对象声明都是一样的
定义格式: const 数据类型 常量名 = 常量值;
数据类型 const 常量名 = 常量值;

例如: const int a=7; int const a=7; (符号常量)
int b=5;
const int *p=&b;
int const *p=&b;( 常指针)
const int &m=b;
(常引用)
const Point pt;
Point const pt; // 常对象不能更新
常指针和常引用在功能上有所限制,就是不能通过他们更改其指向的变量的数据(值)

2.
指针常量
定义格式: 数据类型 *const 指针常量 = 常量值;
char ch,*const pch=&ch;( 我是一步完成的,你也可以分开)
也就是说这个指针本身是个常量,不可改变,即它所指向的地址是固定的。但, ch 是可以改变的。

************************************


下面是 MSDN 中关也常对象的说法
///
Initializing Pointers to const Objects
A pointer to a const object can be initialized with a pointer to an object that is not const, but not vice versa. For example, the following initialization is legal:

Window StandardWindow;
const Window* pStandardWindow( &StandardWindow );

In the preceding code, the pointer pStandardWindow is declared as a pointer to a const object. Although StandardWindow is not declared as const, the declaration is acceptable because it does not allow an object not declared as const access to a const object. The reverse of this is as follows:

const Window StandardWindow;
Window* pStandardWindow( &StandardWindow );

The preceding code explicitly declares StandardWindow as a const object. Initializing the nonconstant pointer pStandardWindow with the address of StandardWindow generates an error because it allows access to the const object through the pointer. That is, it allows removal of the const attribute from the object.
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值