class Date
{
public:
Date(int year, int month, int day)
:_year(year), _month(month), _day(day)
{
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
const Date d1(2022, 8, 10);
d1.Print();
return 0;
}
以上这段代码编译器会报错,我们用Date类实例化了一个带有const修饰的对象,然后调用了一下类中的函数,报错意思也就是一个变量的权限不能从仅仅可读,变为可读可写,权限只可以缩小,而不可以放大。
这时需要用到const成员函数,有const修饰的对象,只能调用有const修饰的成员函数
将Print函数改为const成员函数,即可完美运行。
支持这一完美运行的实质是什么呢?
每个成员函数都有一个this指针,而const成员函数,const就是用来修饰this指针的
即const Date& this(const Date* const this),所以当const Date d1(2022,8,10)调用函数时,给this传入的参数是&Date,也就是Date的地址,但是这个指针类型是 const Date*,指向的内容不可改变,则传入this指向的内容也不可以改变
思考以下几个问题:
1. const对象可以调用非const成员函数吗?
答:不可以
2.非const对象可以调用const成员函数吗?
答:可以,权限可以缩小
3. const成员函数内可以调用其它的非const成员函数吗?
答:不可以,权限不可以放大。const成员函数的this指针:const Date& this,调用其他成员函数,就要把this指针当参数传过去,const Date&类型不可以传给Date&
4.非const成员函数内可以调用其它的const成员函数吗?
答:可以,权限可以缩小。与上面过程相反