• Item 10.const成员函数 (Meaning of a Const Member Function)


    Item 10. Meaning of a Const Member Function

    1、何谓const成员函数:
      成员函数名字后面有个const

    2、const成员函数与non-const成员函数的区别:
     区别在于成员函数中的那个看不见的this指针的类型:
     non-const成员函数里this的类型是 X* const,即一个指向不变的this指针
     const 成员函数里this的类型是const X * const,即一个在此成员函数里this的指向和类的内容都不能修改。

    3、想让const成员函数修改非静态的数据成员怎么办?
      在非静态的数据成员前加上mutable 关键字

    4、用const可以用来重载成员函数
    class X {
      public:
        //...
        int &operator [](int index);
        const int &operator [](int index) const;
        //...
    };

    int i = 12;
    X a;
    a[7] = i; // this 为 X *const
    const X b;
    i = b[i]; // this 为 const X *const


  • 相关阅读:
    C++内存管理
    GitHub 简单用法
    Tembin
    git
    js 插件使用总结
    cas sso
    Redis实战
    全面分析 Spring 的编程式事务管理及声明式事务管理
    mybatis
    b2b
  • 原文地址:https://www.cnblogs.com/aiwz/p/6333257.html
Copyright © 2020-2023  润新知