一:const简介
- const修饰只读变量,必须在定义的同时进行初始化
- 编辑器通常不为普通的const只读变量分配内存空间,而是将他们保存在符号表中。
二:const的用途
1.修饰一般变量
const int i=0;
const int j=0;
2.修饰数组
int const arr1[]={1,2,3,4,5};
const int arr2[]={1,2,3,4,5};
3.修饰指针
const int *p; //p可变,p指向的对象不可变
int const* p; //p可变,p指向的对象不可变
int *const p; //p不可变,p指向的对象可变
const int *const p; //指针p和p指向的对象都不可变
4.修饰函数的参数
int add(const int a,const int b);
5.修饰函数的返回值
const int add(int a,int b);
//在另一个连接文件中引用const只读变量
extern const int i;//正确的声明
extern const int j=10;//错误!只读变量的值不能更改
const在C++中的使用
cosnt 修饰类的成员函数
在C++中将const修饰的成员函数称之为const成员函数,const修饰类成员函数,实际修饰的是该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改
- 编辑器对成员函数的处理
class Date{
public:
void disPlay()const{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
private:
int _year;
int _month;
int _day;
}
//编辑器对const修饰的成员函数的处理方式
class Date{
public:
void disPlay(const Date* this){
cout<<this->_year<<"-"<<this->_month<<"-"<<this->_day<<endl;
}
private:
int _year;
int _month;
int _day;
}
【总结】
1.const的成员函数不能调用非const的成员函数
2.非const成员函数可以调用const成员函数
3.const对象不能调用非const成员函数
== 4.非const对象 可以调用所有成员函数==
c++中在函数后面加了const的成员函数可以被非const对象和const对象调用 ,但不加const的成员函数只能被非const对象调用
【原理】
我们都知道在调用成员函数的时候编译器会将对象自身的地址作为隐藏参数传递给函数,在const成员函数中,既不能改变this所指向的对象,也不能改变this所保存的地址,this的类型是一个指向const类型对象的const指针。