C++自学笔记(4)之const

先来看看const与一般变量的关系
int x=3 是一个变量,其值是可以改变的。而const int x=3是常量,更改其值的时候会报错。与#Define x 3相比,使用const定义能检查语法错误

const与指针类型

const int *p=NULL;         const int * const p=NULL;
int const *p=NULL;         int const * const p=NULL;

这几种情况上下分别是完全等价的
int * const p=NULL与第一列不等价
来看一下例子
在这里插入图片描述
这个例子中 const是对*p作为常量,因此可以对p赋值而不可以对*p赋值。

在这里插入图片描述
这里const规定下的p只能指向一个一个值,不能再变换

在这里插入图片描述
这里无论是p还是*p都不能再赋值

const与引用

int x=3;
const int &y=x;
x=10;       //能够正常赋值
y=20;       //报错,因为y是常量

来看一个例子

const int x=3;        int *y=&x;
int x=3;            const int *y=&x;

第一种写法x不可变,而y作为x的指针可变,可能会改变x的值
第二种x可变,指针y不可变,使用这种方法是正确的

猜你喜欢

转载自blog.csdn.net/qq_39672732/article/details/88692362
今日推荐