15,440
社区成员
发帖
与我相关
我的任务
分享
//分别加上和去掉注释来编译这个程序
// Mutable.cpp
// The "mutable" keyword
class Z {
int i;
mutable int j;
public:
Z();
void f() const;
void g();
};
Z::Z() : i(0), j(0) {}
void Z::f() const {
//! i++; // Error -- const member function
j++; // OK: mutable
}
void Z::g(){
i++;
j++;
}
int main() {
const Z zz;
Z tt;
zz.f(); // Actually changes it!
tt.g();
} //
#include <iostream>
#include <iomanip>
using namespace std;
class C
{
public:
C(int i):m_Count(i){}
int incr() const//注意这里的const
{
return ++m_Count;
}
int decr() const
{
return --m_Count;
}
private:
mutable int m_Count;//你可以试着将这里的mutable去掉再编译试试
};
void main()
{
C c1(0),c2(10);
for(int tmp,i=0;i<10;i++)
{
tmp = c1.incr();
cout<<setw(tmp)<<setfill(' ')<<tmp<<endl;
tmp = c2.decr();
cout<<setw(tmp)<<setfill(' ')<<tmp<<endl;
}
}
for example:
A.class Date
{
bool bValid;
...............
void f() const;
};
void Date::f() const
{
bValid = true; //错误不能改变该变量值
.............
}
B.class Date
{
mutable bool bValid;
...............
void f() const;
};
void Date::f() const
{
bValid = true; //正确 能改变该变量值
.............
}