• 【C++】之类和对象 - const成员函数


    1. class Date
    2. {
    3. public:
    4. Date(int year, int month, int day)
    5. :_year(year), _month(month), _day(day)
    6. {
    7. }
    8. void Print()
    9. {
    10. cout << _year << "-" << _month << "-" << _day << endl;
    11. }
    12. private:
    13. int _year;
    14. int _month;
    15. int _day;
    16. };
    17. int main()
    18. {
    19. const Date d1(2022, 8, 10);
    20. d1.Print();
    21. return 0;
    22. }

    以上这段代码编译器会报错,我们用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成员函数吗?

    答:可以,权限可以缩小。与上面过程相反

  • 相关阅读:
    2022.8.30 go语言课程作业
    30分钟使用百度EasyDL实现健康码/行程码智能识别
    Map.get、Map.set、Map.has方法
    离散化模板
    在线小说阅读系统
    C++哈希+哈希改造
    在项目中,为什么有 全英文大写的 变量?
    Kali 无法联网的解决方案,优雅的配置桥接模式
    简单入门linux【一】初识linux
    工作记录:vue-grid-layout 修改 margin 导致 item 高度剧烈变化
  • 原文地址:https://blog.csdn.net/Hello_World_213/article/details/126268747