个人主页:Lei宝啊
愿所有美好如期而遇
将const 修饰的 “ 成员函数 ” 称之为 const 成员函数 , const 修饰类成员函数,实际修饰该成员函数 隐含的 this 指针 ,表明在该成员函数中不能对类的任何成员进行修改。
- class Date
- {
- public:
-
- Date()
- :_year(2023)
- ,_month(10)
- ,_day(28)
- {}
-
- void print() const //const限定this指针,相当于const Date* this
- {
- cout << _year << "-" << _month << "-" << _day << endl;
- }
-
- private:
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
-
- Date a;
- a.print();
-
- return 0;
- }
- class Date
- {
- public:
-
- Date()
- :_year(2023)
- ,_month(10)
- ,_day(28)
- {}
-
- void print1() const //const限定this指针,相当于const Date* this
- {
- cout << _year << "-" << _month << "-" << _day << endl;
- }
-
- void print2()
- {
- cout << _year << "-" << _month << "-" << _day << endl;
- }
-
- private:
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
-
- Date a;
- a.print1();
-
- const Date b;
- b.print1();
-
- return 0;
- }
编译器甚至都没有给出print2这个函数的选项,答案自然是不能,但为什么不能呢?
- class Date
- {
- public:
-
- Date()
- :_year(2023)
- ,_month(10)
- ,_day(28)
- {}
-
- void print1() const //const限定this指针,相当于const Date* this
- {
- cout << _year << "-" << _month << "-" << _day << endl;
- }
-
- void print2()
- {
- cout << _year << "-" << _month << "-" << _day << endl;
- }
-
- private:
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
-
- Date a;
- a.print1();
-
- const Date b;
- b.print1();
-
- Date c;
- c.print2();
-
- return 0;
- }
权限放大不可以,但可以有权限的缩小,c对象成员变量可以修改,也可以不修改,他的别名成员变量不可以修改是合理的。
这里是权限的缩小,是OK的