强制类型转换:
static_cast、interpret_cast const_cast和dynamic_cast
1. static_cast static_cast用来进用行比较“自然”和低风险的转换, 比如整型和实数型、字符型之间互相转换。 static_cast不能来在不同类型的指针之间互相转换,也 不能用于整型和指针之间的互相转换,也不能用于不同类 型的引用之间的转换。
2. reinterpret_cast
reinterpret_cast用来进行各种不同类型的指针之间的转换、不同类型的引用 之间转换、以及指针和能容纳得下指针的整数类型之间的转换。转换的时候, 执行的是逐个比特拷贝的操作。
3. const_cast:
用来进行去除const属性的转换。将const引用转换成同类型的非const引用, 将const指针转换为同类型的非const指针时用它。例如: const string s = “Inception”; string & p = const_cast(s); string * ps = const_cast(&s); // &s的类型是const string *
4. dynamic_cast :
dynamic_cast专门用于将多态基类的指针或引用,强 制转换为派生类的指针或引用,而且能够检查转换的 安全性。对于不安全的指针转换,转换结果返回NULL 指针。 dynamic_cast不能用于将非多态基类的指针或引用, 强制转换为派生类的指针或引用。
Derived & r = dynamic_cast(b); 那该如何判断该转换是否安全呢? 答案:不安全则抛出异常。
In-Video Quiz:
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.