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 生日广州男生祝福语简短