1. 程式人生 > >C++關鍵字的詳解 ---- mutable關鍵字

C++關鍵字的詳解 ---- mutable關鍵字

  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修飾的函式裡面也能被修改.