/**/
/*************************************************
* 常量成员函数的含义(成员函数 + const)
*
* 在类的 非 常量成员函数中,this指针类型是 X *const(指
* 针常量),而在 常量成员函数中,this指针类型是const X *const
* 不能被修改,这就是常量成员函数和非常量成员函数的区别.
*************************************************/
//
例1
class
X
...
{
private:
static int expensiveOperation();
int *buffer_;
bool isComputed_;
int computedValue_;
public:
X():buffer_(0),isComputed_(false)
...{}
//...
void setBuffer()
...{
int *tmp = new int[MAX];
delete[] buffer_;
buffer_ = tmp;
}
void modifyBuffer(int index,int value) const //相当不道德 -_-!
...{
buffer_[index] = value;
}
int getValue() const
...{
if(!isComputed)
computedValue_ = expensiveOperation(); //错误
isComputed_ = true; //错误
}
return computedValue_;
}
;

/**/
/*************************************************
* 如果我们需要在常量函数中修改类成员怎么办?
* 类的非静态变量数据成员可以声明为mutable,这将允许
* 它们的值可以被常量成员函数(当然也包括成员函数)所修改.
*************************************************/
//
例2
class
X
...
{
private:
static int expensiveOperation();
int *buffer_;
mutable bool isComputed_; //注意 mutable
mutable int computedValue_; //注意 mutable
public:
X():buffer_(0),isComputed_(false)
...{}
//...
void setBuffer()
...{
int *tmp = new int[MAX];
delete[] buffer_;
buffer_ = tmp;
}
void modifyBuffer(int index,int value) const //相当不道德 -_-!
...{
buffer_[index] = value;
}
int getValue() const
...{
if(!isComputed)
computedValue_ = expensiveOperation(); //正确
isComputed_ = true; //正确
}
return computedValue_;
}
;

/**/
/*************************************************
* 下面通过操作符的重载来深刻理解常量成员函数
*************************************************/
//
例3
class
X
...
{
public:
//...
int &operator [](int index); // ①
const int &operator [](int index) const; //②
//...
}
;
void
main()
...
{
int i = 10;
X a;
a[5] = i; //重载 ①
const X b;
i = b[5]; //重载 ②
}

class
X
...
{
public:
X operator + (const X &rightArg); //左边的参数是非常量
X operator + (const X &rightArg) const; //左边的参数是常量
}
;
本文探讨了C++中常量成员函数的概念及其用途,并详细解释了如何使用mutable关键字来修改常量成员函数中的类成员变量。此外,还通过操作符重载的例子进一步加深了对常量成员函数的理解。

284

被折叠的 条评论
为什么被折叠?



