Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2295896
  • 博文数量: 252
  • 博客积分: 5472
  • 博客等级: 大校
  • 技术积分: 3107
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-17 18:39
文章分类

全部博文(252)

文章存档

2012年(96)

2011年(156)

分类: C/C++

2012-05-23 10:31:44

在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修饰的函数里面也能被修改。


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