Question about const_cast in c++(c++中关于const_cast的问题)
问题描述
全部:这是引自 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的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++中关于const_cast的问题
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
