C++ mutable 数据成员

本文参考资料来源于 <Professional C++, 4th Edition>

在关于上一章的 const 中, 我们提到了 mutable, 就来详细介绍一下:

在 const 后缀的成员函数中, 我们通常情况下不能在该函数中改变任何值

但是有一种很特殊的数据成员: mutable

我们有的时候没有注意到在 const 后缀的成员函数中更改了某些的值, 则会引起报错, 如:

 

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 class PERSON
 5 {
 6 private:
 7     string name="TweeChalice";
 8     int get_ans=0;
 9 public:
10     string GetName() const;
11     int GetAns() const;
12 };
13 string PERSON::GetName() const
14 {
15     get_ans++;// Error!!! get_ans is a read-only object
16     return name;
17 }
18 int PERSON::GetAns() const
19 {
20     return get_ans;
21 }
22 int main()
23 {
24     PERSON c;
25     c.GetName();
26     c.GetName();
27     cout<<c.GetName()<<endl;
28     cout<<c.GetAns()<<endl;
29     return 0;
30 }

 

 

 

 

在第14行中, 我没有意识地将统计器累加, 而这种情况是时常发生的, 很容易没有意识到这个函数是const后缀

那怎么办? 如果既想保留 const 后缀, 又需要变更值怎么办?--------mutable 数据成员

mutable 数据成员可以让一个函数在逻辑上是 const 后缀, 但是又可以允许改动标有 mutable 前缀的量

很简单, 只需要在 int get_ans=0 前面加上 "mutable" 即可

 

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 class PERSON
 5 {
 6 private:
 7     string name="TweeChalice";
 8     mutable int get_ans=0;//Attention!!!
 9 public:
10     string GetName() const;
11     int GetAns() const;
12 };
13 string PERSON::GetName() const
14 {
15     get_ans++;
16     return name;
17 }
18 int PERSON::GetAns() const
19 {
20     return get_ans;
21 }
22 int main()
23 {
24     PERSON c;
25     c.GetName();
26     c.GetName();
27     cout<<c.GetName()<<endl;
28     cout<<c.GetAns()<<endl;
29     return 0;
30 }

 

这样一来, 编译器就会被强制地被认为get_ans可以被改动

 

转载于:https://www.cnblogs.com/tweechalice/p/11437963.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值