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


posted on 2005-04-11 19:10  张大大123  阅读(113)  评论(0编辑  收藏  举报

导航