C++ - 常量成员函数的含义
2011-04-20 01:15
330 查看
在类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 常量成员函数的含义
*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 常量成员函数的含义
相关文章推荐
- C++-必知必会_常量成员函数的含义(条款10)
- 成员函数声明为常量的解释--C++学习笔记
- C++里的静态成员函数(不能用const的原因+static在c++中的第五种含义)(转)
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++ 常量对象,成员函数,引用
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++学习之const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++里的静态(static)成员函数(不能用const的原因+static在c++中的第五种含义)
- 关于C++中的常量成员函数
- C++的一些基本功,包括对常量成员函数的一些特殊说明
- C++的常量成员函数
- C++ 中常量成员函数
- C++必知必会之(10)常量成员函数的含义
- c++常量成员函数
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++常量成员函数特殊说明
- C++常量详解二(常量形参,常量返回值,常量成员函数)
- C++基础:常量成员函数特殊说明
- C++里的静态成员函数(不能用const的原因+static在c++中的第五种含义)