C++之const

const(控制变量是否可以变化)
const int x=3;(则此时x为常量,不可进行再赋值)
const与指针类型
const int *p=NULL;
int const *p=NULL;(两种写法完全等价)
int *const p=NULL;
const int *const p=NULL;
int const *const p=NULL;(这两种写法也是完全等价的)

int x=3const int *p=&x; *p=4(错误,因为const指定的为*p);p=&y;(正确)
int x=3; const int *const p=&x; p=&y(错误,因为const指向的为p,只能为x的地址)

const与引用
int x=3const int &y=x; y=10(错误,y通过const限定只能为x的别名,值为3)

总结:
const int x=3int *y=&x;(这种写法是错误的因为x本身定义为const,在用一个可变的指针指向,那么就有用指针改变x值得风险,这是系统所不允许的);
int x=3const int *y=&x;(正确,这样保证了指针对x只有可读性,而没有可写性)
无欲则刚 关心则乱
原文地址:https://www.cnblogs.com/xjyxp/p/11232672.html