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

C++关键字的详解 ---- mutable关键字

2015-10-13 20:37 267 查看
mutable的中文翻译是:易变的,性情不定的,跟constant(既C++中的const)是反义词.

在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中.

例子解释

#include <iostream>
using namespace std;

class HuangwenMutable
{
public:
huangwenMutable(){temp=0;}
int Output() const
{
return temp++; //error C2166: l-value specifies const object
}
private:
int temp;
};

int main()
{
HuangwenMutable huangwenMutable;
cout<<huangwenMutable.Output()<<endl;
return 0;
}


显然temp++不能用在const修饰的函数里.

#include <iostream>
using namespace std;

class HuangwenMutable
{
public:
huangwenMutable(){temp=0;}
int Output() const
{
return temp++; //error C2166: l-value specifies const object
}
private:
mutable int temp;
};

int main()
{
HuangwenMutable huangwenMutable;
cout<<huangwenMutable.Output()<<endl;
return 0;
}


计数器temp被mutable修饰,那么它就可以突破const的限制,在被const修饰的函数里面也能被修改.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++关键字的详解