在c++中const修饰的成员函数是无法修改变量内容的,修改变量是编译器会报错。
但这个还是可以有例外滴,可以使用mutable关键字修饰变量,这样const成员函数就可以修改变量啦。
下面是例程:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
class C
{
public:
C(int i): m_count(i){}
int incr() const
{
return ++m_count;
}
int decr() const
{
return --m_count;
}
private:
mutable int m_count;
};
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;
}
return 0;
}
结果如下图: