加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++ mutable 数据成员

发布时间:2020-12-16 09:17:35 所属栏目:百科 来源:网络整理
导读:本文参考资料来源于 Professional C++,4th Edition 在 const 后缀的成员函数中,我们 通常情况下 是 不能在该函数中改变任何值 但是有一种很特殊的数据成员: mutable 我们有的时候没有注意到在 const 后缀的成员函数中更改了某些的值,则会引起报错,如: ? 1 #i

本文参考资料来源于 <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可以被改动

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读