C++ 中的mutable关键字

文章转自:https://blog.csdn.net/liyuanbhu/article/details/50365287
版权归原作者!


在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 这个关键字用的地方不多。了解这些也就够了。

猜你喜欢

转载自blog.csdn.net/libing_zeng/article/details/80728233