常指针与指针常量的区别?以及常对象和常引用、常指针与指针常量定义上的区别,
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/19 03:35:32
常指针与指针常量的区别?以及常对象和常引用、常指针与指针常量定义上的区别,
常指针与指针常量的区别?以及常对象和常引用、常指针与指针常量定义上的区别,
常指针与指针常量的区别?以及常对象和常引用、常指针与指针常量定义上的区别,
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属性
下面是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电脑吧讨论!