如果想要建立一个const成员函数,但仍然想在对象里改变些数据,可以按
位const和按逻辑 const
按位const意思是对象每个字节都是固定的,所以对象的每个位映像从不改变
按逻辑const意思是,虽然整个对象从概念上讲是不变的,但是可以以成员为
单位改变
按位const成为过去,称为 "强制转换常量性(casting away constness)"。
以相当奇怪的方式执行
this关键字产生当前对象的地址,把强制转换成指向当前类型对象的指针
看来this已经是所需的指针,但是,在const成员函数内部,实际上是一个
const指针
应把const指针转换成一个普通指针,可以在那个按位const运算去掉常量性
//: C08:Castaway.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// "Casting away" constness
class Y {
int i;
public:
Y();
void f() const;
};
Y::Y() { i = 0; }
void Y::f() const {
//! i++; // Error -- const member function
((Y*)this)->i++; // OK: cast away const-ness
// Better: use C++ explicit cast syntax:
(const_cast<Y*>(this))->i++;
}
int main() {
const Y yy;
yy.f(); // Actually changes it!
} ///:~
这种方法可行,过去代码可看到这种用法,但不是首选的技术
问题是:常量性的缺乏隐藏在成员函数的定义中,并且没有来自类接口的
线索知道对象的数据实际上被修改,除非用户不能见到源代码
为了公开 对象的数据实际上被修改,在类声明里使用关键字mutable,以
指定一个特定的数据成员可以在一个const对象里被改变
//: C08:Mutable.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// The "mutable" keyword
class Z {
int i;
mutable int j;
public:
Z();
void f() const;
};
Z::Z() : i(0), j(0) {}
void Z::f() const {
//! i++; // Error -- const member function
j++; // OK: mutable
}
int main() {
const Z zz;
zz.f(); // Actually changes it!
} ///:~
现在,类用户可从声明里看到哪个成员能够用const成员函数进行修改
无输出