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

来源:互联网 发布:关于大数据的论文 编辑:程序博客网 时间:2024/05/25 19:57
  1. mutable的中文翻译是:易变的,性情不定的,跟constant(既C++中的const)是反义词.
  2. 在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修饰的函数里面也能被修改.

0 0