要搞清楚const对指针修饰的结果,首先要搞清楚 *p 和 p 的区别。可以简单理解,*p存储的是指针的值,p存储的是指针的地址。
const关键字的作用是限制操作,const int *p 此时const后面跟着 *p ,const就限制了 *p 的操作,指针的值不能修改;int * const p 此时const后面跟着 p ,const限制了 p 的操作,这时指针的地址不能修改;const int * const p 此时const同时修饰 *p 和 p ,指针的值和地址都不能修改。
#include <string>
#include <iostream>
int main()
{
int a = 10, b = 20,c=30;
//const 修饰*p
const int *p1 = &a;
*p1 = 0;//error
p1 = &b;
//const修饰p
int * const p2 = &a;
*p2 = 0;
p2 = &b;//errror
//const同时修饰*p和p
const int * const p3 = &c;
*p3 = 0;//error
p3 = &b;//error
system("pause");
return 0;
}```
本文详细介绍了C++中const关键字对指针的影响。分别讨论了const修饰指针值、指针本身以及同时修饰两者的情况,并通过示例代码展示了各种情况下指针的使用限制。通过对*p和p的不同修饰,明确了const在指针类型中的作用。
204

被折叠的 条评论
为什么被折叠?



