全部:这是引自 Effective C++ 3rd edition
all: this is quoted from Effective C++ 3rd editiion
const_cast 通常用于抛弃对象的常量性.这是唯一可以做到这一点的 C++ 风格的强制转换.
const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this.
我的问题是 const_cast 可以为非常量对象添加常量性吗?其实我写了一个小程序来验证我的想法.
My question is can const_cast add constness to a non-const object? Actually i wrote a small programme trying to approve my thought.
class ConstTest
{
public:
void test() {
printf("calling non-const version test const function
");
}
void test() const{
printf("calling const version test const function
");
}
};
int main(int argc,char* argv){
ConstTest ct;
const ConstTest cct;
cct.test();
const_cast<const ConstTest&>(ct).test();//it is wrong to write this statement without the '&',why
}
省略&"导致以下错误:
Omitting the '&' incurs error below:
错误 C2440:const_cast":无法从ConstTest"转换为const ConstTest"
error C2440: 'const_cast' : cannot convert from 'ConstTest' to 'const ConstTest'
说明const_cast可以增加constness,但是好像必须强制转换为一个对象引用,这个引用有什么魔力?
It shows that const_cast can add constness,but seems like you have to cast to a object reference, what is the magic of this reference ?
你不需要const_cast
来添加constness:
You don't need const_cast
to add constness:
class C;
C c;
C const& const_c = c;
反过来需要一个const_cast
const C const_c;
C& c = const_cast<C&>(const_c);
但是如果您尝试在 c
上使用非常量操作,则行为未定义.
but behavior is undefined if you try to use non-const operations on c
.
顺便说一句,如果不使用引用,则要制作对象的副本:
By the way, if you don't use a reference, a copy of the object is to be made:
C d = const_c; // Copies const_c
这篇关于c++中关于const_cast的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!