const关键字简单理解

const是一个C语言的关键字,它限定一个变量不允许被改变。使用const在一定程度上可以提高程序的安全性和可靠性。

C++中函数声明与调用会有一个默认的this指针变量,如下所示:

//void RegisterCGoods(CGoods *const this, char Name[], int Amount, float Price)
void RegisterCGoods(char Name[], int Amount, float Price)

//RegisterCGoods(&c1,"C++",10,12);
c1.RegisterCGoods("C++",10,12);

方法:判断const在*的左边还是右边,const封锁的是右边

const int * p; //*p是常量,不能修改
int const * p; //*p是常量,不能修改
两种方式没有区别

int * const p; //p是常量,不能修改

const int * const p; //两个位置都是常量,都不能修改

还有一种情况const在函数的后面

void RegisterCGoods(CGoods *const this, char Name[], int Amount, float Price) const
这种情况等同于 :

//void RegisterCGoods(const CGoods *const this, char Name[], int Amount, float Price)

即封锁的是*this的值。


const引用:

常变量只能拿常变量引用;变量可以用变量引用,也可以用常变量引用
const int x = 100; int &y = x; ×
const int x = 100; const int &y = x;
int x = 100; conost int &y = x;
const double x = 12.34; const int &y = x; 可以实现 但x与y由于类型不同 地址也不同 不是引用开辟了空间 而是引用的不是原先的地址空间 而是临时的空间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值