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 高考祝福语简短10字
13 简短朋友旅行祝福语大全
14 送蛇的祝福语简短
15 很暧昧的简短祝福语
16 上班收到花束祝福语简短
17 牛年女神节祝福语简短
18 药店祝福语简短10字