C++ 中的 mutable 關鍵字?


在此,我們將瞭解 C++ 中的 mutable 關鍵字。mutable 是 C++ 中的儲存類之一。Mutable 資料成員是可以始終被修改的那種成員。即使物件是常量型別。當我們需要一個成員作為變數,而另一個作為常量時,我們可以使其變為 mutable。讓我們看一個示例來了解這個想法。

示例

#include <iostream>
using namespace std;
class MyClass{
   int x;
   mutable int y;
   public:
   MyClass(int x=0, int y=0){
      this->x = x;
      this->y = y;
   }
   void setx(int x=0){
      this->x = x;
   }
   void sety(int y=0) const { //member function is constant, but data will be changed
      this->y = y;
   }
   void display() const{
      cout<<endl<<"(x: "<<x<<" y: "<<y << ")"<<endl;
   }
};
int main(){
   const MyClass s(15,25); // A const object
   cout<<endl <<"Before Change: ";
   s.display();
   s.setx(150);
   s.sety(250);
   cout<<endl<<"After Change: ";
   s.display();
}

輸出

[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]

如果我們透過刪除行 [s.setx(150);] 來執行程式,則 −

輸出

Before Change:
(x: 15 y: 25)
After Change:
(x: 15 y: 250)

更新於: 20-Aug-2019

783 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.