【3】学习C++之const关键字的使用

在C++中,const关键字是控制变量是否可以变化的,是否能够用好const关键字是区别小白和大佬的重要指标(大雾)。

1.const与基本数据类型

int a = 10;         //a是变量,a的值可以在后续操作中进行更改。
const int b = 10;//b是常量,b的值不能进行更改,进行更改操作会报错。

2.const与指针类型

以下两种写法是等价的:

int const a = 10;
const int a = 10;

以下两种写法还是等价的:

const int *const a = NULL;
int const *const a = NULL;

但是以下两种写法是不等价的:

int const *a = NULL;
int *const a = NULL;

常见的用法与错误:

int x = 10;
int y = 20;
const int *p = &x;
p = &y;//此操作正确
*p = 30;//此操作错误
//可以理解为,const修饰的是*p,即*p所存储的东西是固定的,不能去改变,然而p没有被const修饰,所以可以对p的存储的东西进行更改。
int x = 10;
int y = 20;
int *const p = &x;
p = &y;//此操作错误
//此时,const修饰的是p,所以对p存储的地址信息是不能进行更改的,相应的可以对*p进行修改
const int a = 10;
const int b = 20;
const int *const p = &a;
p = &b;//错误
*p = 30;//错误、
//p和*p全部都被const所修饰,所以不能对p和*p进行更改操作
const int x = 10;
int *y = &x;
//理论上,*y可以进行修改操作,但是这种行为会带来巨大的风险,所以编译器会报错

 一句话简单的概括就是:如果关键字const出现在星号左边,表示被指物是常量;如果出现在星号的右边,表示指针自身是常量。

原文地址:https://www.cnblogs.com/H2Rain/p/10669544.html