const关键字简单理解

来源:互联网 发布:淘宝卖家好评不返现 编辑:程序博客网 时间:2024/05/19 17:06

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由于类型不同 地址也不同 不是引用开辟了空间 而是引用的不是原先的地址空间 而是临时的空间