关键字:C++, mutable
本文主要说明如何在一个const成员函数中修改类的成员变量,本人在阅读当中偶得,不见得对各位有多大实用价值。针对菜鸟,老鸟们不用看了。
大家知道如果把一个类的成员函数声明为const,则表示该函数不会修改类的成员变量,像下面这样:
class ConstFunc
{
public:
ConstFunc(){i = j = 1;};
void ConstFunction() const;
void Tell() const;
private:
int i;
int j;
};
void ConstFunction() const
{
cout << "i=" << i << ", j=" << j << endl;
}
void ConstFunction() const
{
//i ++; //Would cause an error
//j ++; //Would cause an error
}
void main()
{
ConstFunc myConstFunc;
myConstFunc.f();
myConstFunc.Tell();
}
《C++编程思想》7.4.3节里,作者提到一个C++关键字mutable,用这个修饰符限定的变量可以被一个声明为const的成员函数修改。上面例子略作修改如下:
class ConstFunc
{
public:
ConstFunc(){i = j = 1;};
void ConstFunction() const;
void Tell() const;
private:
int i;
mutable int j; //Declared as mutable here
};
void ConstFunction() const
{
cout << "i=" << i << ", j=" << j << endl;
}
void ConstFunction() const
{
//i ++; //Would cause an error
j ++; //OK here!
}
void main()
{
ConstFunc myConstFunc;
myConstFunc.f();
myConstFunc.Tell();
}
小弟才疏学浅,还没有碰上实际当中运用mutable关键字的现象。
另外稍稍提醒,const的用法大家都熟了吗?不妨看看下面的小测试吧:
请分别说明下面声明的含义:
const int* x;
int const* x;
int* const x;
const int* const x;
int const* const x;