const关键字的深入理解

来源:互联网 发布:php项目开发 编辑:程序博客网 时间:2024/06/06 14:19

const作为c++语言的关键字,我们的设计原则是,尽量多使用const变量:

那么为什么是这样呢,c++语言引入指针的不足之处就是内存的管理变复杂,容易出现引用出错,所以我们有时需要对不能够更改的地址空间进行保护即只能读,不能写,这个保护的方式就是定义为const,由const修饰的内存空间不能够写。

通过const的使用可以保护容易受破坏的内存,提高程序的稳健性,使得违规写错误在编译时期就暴露出来,从而及时修改。

 

const的用法:修饰变量,修饰指针和引用,修饰成员函数三种,我们分别讨论:

1.修饰常量是最简单的,最基本的用法:
const int a=100; b的内容不变,b只能是100也就是声明一个int类型的常量(#define b =100)
int const b=100; //和上面作用一样

const指针和引用一般用在函数的参数中
int* m = &a; //出错,常量只能用常指针
int c= 1;const int*pc = &c;//常指针可指向常量

2.修饰指针和引用,const在*号左侧指指针的值不能改变,const在*号右侧指指针指向的数值不能改变;

const int* pa = &a; //指针指向的内容为常量(就是b的值不变)
int const *a = &b; //指针指向的内容为常量(就是b的值不变)*p=3//error
int* const a = &b; //指针为常量,不能更改指针了如 a++但可以改值*p=3;

从这可以看出const放在*左侧修饰的是指针的内容,const放在*右侧修饰的是指针
本身.

const引用的用法和指针一样
int const & a=b; 和指针一样
const int& a=b; 和指针一样
但没有 int& const a=b 的用法因为引用不能做移位运算,但只是出个warning

3.const对于成员函数:如

const char* why()const{return "test"}; 

const char* 这里的const表示返回内容不可更改,如: 

X.why() = "hello"; //错误 

why()const表示该函数不修改数据成员的值,如: 

class X 

int a; 
public: 
const char* why()const{a = 2;return "test"}; // 错误!! 
}; const char* why()const{return "test"}; 

const char* 这里的const表示返回内容不可更改,如: 

X.why() = "hello"; //错误 

why()const表示该函数不修改数据成员的值,如: 

class X 

int a; 
public: 
const char* why()const{a = 2;return "test"}; // 错误!! 
}; const char* why()const{return "test"}; 

const char* 这里的const表示返回内容不可更改,如: 

X.why() = "hello"; //错误 

why()const表示该函数不修改数据成员的值,如: 

class X 

int a; 
public: 
const char* why()const{a = 2;return "test"}; // 错误!! 
};

原创粉丝点击