在类X的非常量成员函数中,this指针的类型为X *const。也就是说,它是指向非常量X的常量指针。而在类X的常量成员函数中,this的类型为const X * const。也就是说,是指向常量X的常量指针。这就是常量成员函数和非常量成员函数的区别。
对成员函数的this指针类型加上常量修饰符,就可以解释函数重载解析是符合区分一个成员函数的常量和非常量版本的。
有时候一个真的应该被声明为常量的成员函数必须要修改其对象,这种情形的正确方式是将有关数据成员声明为mutable;不要试图去在此常量函数中,对this进行const cast!!!
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_;
}
int
TrygetValue()
const
{
if
(
!
isComputed){
X * const aThis = const_cast<X * const>(this);
//
!!!糟糕的念头
aThis ->
computedValue_ =
expensiveOperation();
isComputed_
=
true
;
}
return
computedValue_;
}
}
;
不少精彩的例子详见: C++必知必会(C++ common knowledge)-----条款10 常量成员函数的含义