声明为mutable性质的成员是可以被const成员函数修改的,这个关键词的作用不是要突破const才有的,而是另有适用场合。如下:
1.追踪const成员函数的执行次数:
#include <iostream>
using namespace std;
class A{
public:
A():c(0){}
int a;
mutable int c;
void show()const{c++; cout << "函数show已经执行了:"<< c << "次。" << endl;}
};
int main(){
cout << "ok" << endl;
A a;
a.show();
a.show();
a.show();
return 1;
}
2.保存const成员函数计算的中间值:
#include <iostream>
using namespace std;
class A{
public:
A():a(100),c(0){}
int a;
mutable int c;
void calc(int x, int y)const
{
c = x * y * a;
cout << "const函数clac保存的中间计算结果是:" << c << endl;}
};
int main(){
cout << "ok" << endl;
A a;
a.calc(12,13);
return 1;
}