Chinaunix首页 | 论坛 | 博客
  • 博客访问: 956357
  • 博文数量: 120
  • 博客积分: 6454
  • 博客等级: 准将
  • 技术积分: 1739
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-28 17:45
文章分类

全部博文(120)

文章存档

2014年(1)

2013年(1)

2012年(11)

2011年(16)

2010年(6)

2009年(11)

2008年(30)

2007年(44)

分类: C/C++

2011-10-28 09:49:14

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

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

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

  下面是一个小例子: 
  1. class ClxTest
  2. {
  3.  public:
  4.   void Output() const;
  5. };

  6. void ClxTest::Output() const
  7. {
  8.  cout << "Output for test!" << endl;
  9. }

  10. void OutputTest(const ClxTest& lx)
  11. {
  12.  lx.Output();
  13. }
  类ClxTest的成员函数Output是用来输出的,不会修改类的状态,所以被声明为const的。

  函数OutputTest也是用来输出的,里面调用了对象lx的Output输出方法,为了防止在函数中调用其他成员函数修改任何成员变量,所以参数也被const修饰。

  如果现在,我们要增添一个功能:计算每个对象的输出次数。如果用来计数的变量是普通的变量的话,那么在const成员函数Output里面是不能修改该变量的值的;而该变量跟对象的状态无关,所以应该为了修改该变量而去掉Output的const属性。这个时候,就该我们的mutable出场了——只要用mutalbe来修饰这个变量,所有问题就迎刃而解了。

  下面是修改过的代码:
  1. class ClxTest
  2. {
  3.  public:
  4.   ClxTest();
  5.   ~ClxTest();

  6.   void Output() const;
  7.   int GetOutputTimes() const;

  8.  private:
  9.   mutable int m_iTimes;
  10. };

  11. ClxTest::ClxTest()
  12. {
  13.  m_iTimes = 0;
  14. }

  15. ClxTest::~ClxTest()
  16. {}

  17. void ClxTest::Output() const
  18. {
  19.  cout << "Output for test!" << endl;
  20.  m_iTimes++;
  21. }

  22. int ClxTest::GetOutputTimes() const
  23. {
  24.  return m_iTimes;
  25. }

  26. void OutputTest(const ClxTest& lx)
  27. {
  28.  cout << lx.GetOutputTimes() << endl;
  29.  lx.Output();
  30.  cout << lx.GetOutputTimes() << endl;
  31. }
  计数器m_iTimes被mutable修饰,那么它就可以突破const的限制,在被const修饰的函数里面也能被修改。

阅读(1215) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~