C++中四种类型转换以及const_cast是否能改变常量的问题

本文详细介绍了C++中的四种类型转换:const_cast、static_cast、reinterpret_cast和dynamic_cast。重点讨论了const_cast如何移除对象的常量性,以及在尝试修改const对象时,编译器的底层处理方式,揭示了const对象在某些情况下并非真正不可变的原理。
摘要由CSDN通过智能技术生成

we have four specific casting operators:dynamic_castreinterpret_caststatic_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)


一、对C++中四种类型转换总结如下:

 
const_cast<T>(expr)

用来移除对象的常量性(cast away the constness)
const_cast一般用于指针或者引用
使用const_cast去除const限定的目的不是为了修改它的内容
使用const_cast去除const限定,通常是为了函数能够接受这个实际参数


static_cast<T>(expr)

编译器隐式执行的任何类型转换都可以由static_cast完成
当一个较大的算术类型赋值给较小的类型时,可以用static_cast进行强制转换。

可以将void*指针转换为某一类型的指针

可以将基类指针强制转换为派生类指针,但是不安全。
无法将const转化为nonconst,这个只有const_cast才可以办得到


reinterpret_cast<T>(expr) 
 
“通常为操作数的位模式提供较低层的重新解释”也就是说将数据以二进制存在形式的重新解释。
int i;
char *p = "This is a example.";
i = reinterpret_cast<int>(p);
//此时结果,i与p的值是完全相同的。


int *ip
char *pc = reinterpret_cast<char*>(ip);
// 程序员需要记得pc所指向的真实对象是int型,并非字符串。
// 如果将pc当作字符指针进行操作,可能会造成运行时错误
// 如int len = strlen(pc);

多重继承时reinterpret_cast不安全。static_cast会根据父子类指针转换的偏移量转换到正确地址,而reinterpret_cast不会。

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cassert>
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值