mutalbe的中文意思是“可变的,易变的”,跟constant(既C++中的const)是反义词。
在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。
我们知道,如果类的成员函数不会改变对象的状态,那么这个成员函数一般会声明成const的。但是,有些时候,我们需要在const的函数里面修改一些跟类状态无关的数据成员,那么这个数据成员就应该被mutalbe来修饰。
以下代码如果要在matest中进行修改m_a的值,就得在定义const A a,去掉const,并且在A类方法的声明时去掉const,但是mutable可以突破这层限制。
1 #include <iostream>
2
3 using namespace std;
4
5 class A
6 {
7 public:
8 A(int a):m_a(a){}
9 void matest()const;
10 void macout()const
11 {
12 cout << m_a << endl;
13 }
14 private:
15 int m_a;
16 };
17
18 void A::matest() const
19 {
20 //m_a = 10;//被const修饰的函数不允许修好任何类状态值(类里面的数据)
21 cout << m_a << endl;
22 }
23
24 int main()
25 {
26 const A a(1);
27 a.macout();//用const修饰的一个类使用一个const修饰的方法
28 return 0;
29 }
1 #include <iostream>
2
3 using namespace std;
4
5 class A
6 {
7 public:
8 A(int a):m_a(a){}
9 void matest()const;
10 void macout()const
11 {
12 cout << m_a << endl;
13 }
14 private:
15 mutable int m_a;
16 };
17
18 void A::matest() const
19 {
20 m_a = 10;//在定义时用mutable来突破这层限制
21 cout << m_a << endl;
22 }
23
24 int main()
25 {
26 const A a(1);
27 a.macout();//用const修饰的一个类使用一个const修饰的方法
28 return 0;
29 }
分类:
C/C++
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)