常指针与指针常量的区别?

常指针与指针常量的区别?以及常对象和常引用、常指针与指针常量定义上的区别,顺便解释一下!谢谢!

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属性
**********************************************

*******我们可以总结一下********
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.
///////////////////////////////////////

有问题我们再到HiKe电脑吧讨论!
来源:http://hike.bokee.com/6169539.html

参考资料:http://hike.bokee.com/6169539.html

温馨提示:答案为网友推荐,仅供参考
相似回答