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 婶婶拜年祝福语大全简短