现代C++学习笔记之二入门篇2,数据转换
2024-10-20 13:47:27
static_cast: 这种强制转换只会在编译时检查。 如果编译器检测到您尝试强制转换完全不兼容的类型,则static_cast会返回错误。 您还可以使用它在基类指针和派生类指针之间强制转换,但是,编译器在无法分辨此类转换在运行时是否是安全的。
dynamic_cast: dynamic_cast在运行时检查基类指针和派生类指针之间的强制转换。 dynamic_cast 是比 static_cast 更安全的强制类型转换,但运行时检查会带来一些开销。
const_cast: const_cast转换为 const 的变量,或者将非 const 变量转换为 const。 通过使用这个操作符强制转换 const 就像使用C样式转换一样容易出错,不同之处在于使用const-cast 不太可能意外地执行转换。 有时候你只能强制转换 const 的变量,例如,传递 const 变量到一个非 const 参数的函数中。
void Func(double& d) { ... }
void ConstCast()
{
const double pi = 3.14;
Func(const_cast<double&>(pi)); //No error.
}
const_cast
reinterpret_cast : 允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。
const char* str = "hello";
int i = static_cast<int>(str);//error C2440: 'static_cast' : cannot
// convert from 'const char *' to 'int'
int j = (int)str; // C-style cast. Did the programmer really intend
// to do this?
int k = reinterpret_cast<int>(str);// Programming intent is clear.
// However, it is not 64-bit safe.
reinterpret_cast
最新文章
- CSS currentColor 变量的使用
- 使用WordPress搭建自己的博客
- uboot 、内核、文件系统移植
- MTK Android 编译命令
- 对golang服务器开发模式的一些思考
- http 协议的过程
- v3学院带您一起学习FPGA
- 2017/4/26-DOM解析XML文件
- webapp通用选择器:iosselect
- Flume报 Space for commit to queue couldn&#39;t be acquired. Sinks are likely not keeping up with sources, or the buffer size is too tight
- 认识Python和基础知识
- Java实现产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。
- mybatis 中的 xml 配置文件中 ‘<;’、 ‘>;’ 处理
- CF1107
- [js高手之路]深入浅出webpack教程系列2-配置文件webpack.config.js详解(上)
- git找回本地误删的文件
- vip导致的serverConnection closed by foreign host问题
- leetCode题解之Longest Palindrome
- Codeforces 429B Working out(递推DP)
- Linux shell 执行修改配置文件中的内容