C++ mutable 数据成员

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

在 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 数据成员

扫描二维码关注公众号,回复: 7139984 查看本文章

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可以被改动

猜你喜欢

转载自www.cnblogs.com/tweechalice/p/11437963.html