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 妈妈生日祝福语简短励志