首页 > 编程语言 > 详细

C++之const

时间:2019-07-23 17:45:18      阅读:81      评论:0      收藏:0      [点我收藏+]
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只有可读性,而没有可写性)

 

C++之const

原文:https://www.cnblogs.com/xjyxp/p/11232672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!