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.