C++ 的 mutable 關鍵字?


可變資料成員是指即使物件是常量型別,其值也可以在執行時更改的成員。這與常量恰恰相反。

有時邏輯需要只使用一到兩個資料成員作為變數,而另一個作為處理資料的常量。在這種情況下,可變性對於管理類是非常有用的概念。

示例

#include <iostream>
using namespace std;
code
class Test {
   public:
      int a;
   mutable int b;
   Test(int x=0, int y=0) {
      a=x;
      b=y;
   }
   void seta(int x=0) {
      a = x;
   }
   void setb(int y=0) {
      b = y;
   }
   void disp() {
      cout<<endl<<"a: "<<a<<" b: "<<b<<endl;
   }
};
int main() {
   const Test t(10,20);
   cout<<t.a<<" "<<t.b<<"\n";
   // t.a=30; //Error occurs because a can not be changed, because object is constant.
   t.b=100; //b still can be changed, because b is mutable.
   cout<<t.a<<" "<<t.b<<"\n";
   return 0;
}

更新於: 2019 年 8 月 9 日

4K+ 瀏覽

啟動你的 職業

完成課程即可獲得認證

入門
廣告
© . All rights reserved.