C ++中的可变关键字?
在这里,我们将了解C++中的mutable关键字是什么。可变是C++中的存储类之一。可变数据成员就是这种成员,可以随时更改。即使对象是const类型。当我们只需要一个成员作为变量,而另一个则是常量时,则可以使它们可变。让我们看一个例子来了解这个想法。
示例
#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)
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语