• lesson2(补充)关于const成员函数


    个人主页:Lei宝啊 

    愿所有美好如期而遇


    前言:

    将const 修饰的 成员函数 称之为 const 成员函数 const 修饰类成员函数,实际修饰该成员函数 隐含的 this 指针 ,表明在该成员函数中不能对类的任何成员进行修改。
    1. class Date
    2. {
    3. public:
    4. Date()
    5. :_year(2023)
    6. ,_month(10)
    7. ,_day(28)
    8. {}
    9. void print() const //const限定this指针,相当于const Date* this
    10. {
    11. cout << _year << "-" << _month << "-" << _day << endl;
    12. }
    13. private:
    14. int _year;
    15. int _month;
    16. int _day;
    17. };
    18. int main()
    19. {
    20. Date a;
    21. a.print();
    22. return 0;
    23. }
    思考下面的几个问题:
    1. const对象可以调用非const成员函数吗?
    1. class Date
    2. {
    3. public:
    4. Date()
    5. :_year(2023)
    6. ,_month(10)
    7. ,_day(28)
    8. {}
    9. void print1() const //const限定this指针,相当于const Date* this
    10. {
    11. cout << _year << "-" << _month << "-" << _day << endl;
    12. }
    13. void print2()
    14. {
    15. cout << _year << "-" << _month << "-" << _day << endl;
    16. }
    17. private:
    18. int _year;
    19. int _month;
    20. int _day;
    21. };
    22. int main()
    23. {
    24. Date a;
    25. a.print1();
    26. const Date b;
    27. b.print1();
    28. return 0;
    29. }

    编译器甚至都没有给出print2这个函数的选项,答案自然是不能,但为什么不能呢? 

    我们定义的对象b是const类型,他的成员变量不能做修改,那他的别名的成员变量也不能修改,而我们上述代码中b对象不能调用print2函数是因为print2函数有权限放大,所以不能调用。
    2. 非const对象可以调用const成员函数吗?

     

    1. class Date
    2. {
    3. public:
    4. Date()
    5. :_year(2023)
    6. ,_month(10)
    7. ,_day(28)
    8. {}
    9. void print1() const //const限定this指针,相当于const Date* this
    10. {
    11. cout << _year << "-" << _month << "-" << _day << endl;
    12. }
    13. void print2()
    14. {
    15. cout << _year << "-" << _month << "-" << _day << endl;
    16. }
    17. private:
    18. int _year;
    19. int _month;
    20. int _day;
    21. };
    22. int main()
    23. {
    24. Date a;
    25. a.print1();
    26. const Date b;
    27. b.print1();
    28. Date c;
    29. c.print2();
    30. return 0;
    31. }

     

    权限放大不可以,但可以有权限的缩小,c对象成员变量可以修改,也可以不修改,他的别名成员变量不可以修改是合理的。

    3. const成员函数内可以调用其它的非const成员函数吗?
    4. 非const成员函数内可以调用其它的const成员函数吗?

     这里是权限的缩小,是OK的


     

  • 相关阅读:
    【Deep Learning 1】遗传算法GA
    ARM64 linux 中断处理--架构
    从事前端真的没有后端工资高?
    springboot启动流程
    从离线到实时对客,湖仓一体释放全量数据价值
    《Datawhale项目实践系列》发布!
    MFC Windows 程序设计[226]之下拉式列表(附源码)
    网站优化Preload进行预加载的使用方法
    李开复:我家的AI是坠吼的
    【JavaEE】初识网络
  • 原文地址:https://blog.csdn.net/m0_74824254/article/details/134095004