笑看风云

记录生活中的启迪与感动
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++中的mutable关键字

Posted on 2009-12-24 12:50  清晨的风  阅读(260)  评论(0)    收藏  举报

mutalbe的中文意思是“可变的,易变的”,跟constant(既C++中的const)是反义词。

  在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。

  我们知道,如果类的成员函数不会改变对象的状态,那么这个成员函数一般会声明成const的。但是,有些时候,我们需要在const的函数里面修改一些跟类状态无关的数据成员,那么这个数据成员就应该被mutalbe来修饰。

 

 1 class ClxTest
 2 {
 3  public:
 4   ClxTest();
 5   ~ClxTest();
 6 
 7   void Output() const;
 8   int GetOutputTimes() const;
 9 
10  private:
11   mutable int m_iTimes;
12 };
13 
14 ClxTest::ClxTest()
15 {
16  m_iTimes = 0;
17 }
18 
19 ClxTest::~ClxTest()
20 {}
21 
22 void ClxTest::Output() const
23 {
24  cout << "Output for test!" << endl;
25  m_iTimes++;
26 }
27 
28 int ClxTest::GetOutputTimes() const
29 {
30  return m_iTimes;
31 }
32 
33 void OutputTest(const ClxTest& lx)
34 {
35  cout << lx.GetOutputTimes() << endl;
36  lx.Output();
37  cout << lx.GetOutputTimes() << endl;
38 }