C++ mutable 数据成员

Posted tweechalice

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 数据成员

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

 

以上是关于C++ mutable 数据成员的主要内容,如果未能解决你的问题,请参考以下文章

mutable关键字

C++入门const和mutable关键字常函数介绍

C++入门const和mutable关键字常函数介绍

C++中如何可以修改const函数内的成员变量的值?

关键字mutable

C++ 中的 volatile 与 mutable