您的位置:首页 > 编程语言 > C语言/C++

C++ 中的 mutable 关键字

2015-12-20 19:32 423 查看

C++ 中的 mutable 关键字

在C++中,mutable 是为了突破 const 的限制而设置的。可以用来修饰一个类的成员变量。被 mutable 修饰的变量,将永远处于可变的状态,即使是 const 函数中也可以改变这个变量的值。

比如下面这个例子:

#include <iostream>
using namespace std;
class Test
{
public:
Test();
int value() const;

private:
mutable int v;
};
Test::Test()
{
v = 1;
}

int Test::value() const
{
v++;
return v;
}

int main()
{
Test A;
cout <<  A.value() << endl;
return 0;
}


甚至于当 A 这个变量被声明 const 类型时 A.v 还是可以改变的。比如下面的代码。

int main()
{
const Test A;
cout <<  A.value() << endl;
return 0;
}


相对来说,mutable 这个关键字用的地方不多。了解这些也就够了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++