// C++ 强制转换示例
#include <iostream>
using namespace std;
int main() {
// 1. C风格强制转换
double d = 3.14;
int i = (int)d; // C风格的强制转换,将double转换为int
cout << "C风格强制转换: " << i << endl;
// 2. static_cast
double d1 = 3.14;
int i1 = static_cast<int>(d1); // 使用static_cast进行类型转换
cout << "static_cast: " << i1 << endl;
// 3. dynamic_cast
class Base {};
class Derived : public Base {};
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // 使用dynamic_cast进行安全的向下转型
if (derivedPtr) {
cout << "dynamic_cast 成功" << endl;
} else {
cout << "dynamic_cast 失败" << endl;
}
// 4. const_cast
const int ci = 5;
int* p = const_cast<int*>(&ci); // 使用const_cast去掉常量属性
*p = 10;
cout << "const_cast: " << *p << endl;
// 5. reinterpret_cast
int a = 65;
char c = reinterpret_cast<char&>(a); // 使用reinterpret_cast进行位级转换
cout << "reinterpret_cast: " << c << endl;
return 0;
}
C风格强制转换:使用 (type)value
的形式,直接将 value
转换为 type
类型。这种方式虽然简单,但不够安全,容易引发错误。
static_cast:用于基本类型的转换(如 int
到 double
),以及类层次结构中的向上和向下转型。它比C风格的转换更安全,编译器会检查类型是否可以安全转换。
dynamic_cast:主要用于多态类型的指针或引用之间的安全转换,通常用于类继承体系中。如果转换失败,返回 nullptr
或抛出异常(对于引用类型)。
const_cast:用于添加或移除变量的 const
属性。它可以将 const
对象转换为非 const
对象,但这可能会导致未定义行为,应谨慎使用。
reinterpret_cast:用于低级别的重新解释数据,例如将一个整数视为字符。这种转换是危险的,因为它依赖于底层硬件的具体实现,应尽量避免使用。
上一篇:c++ 内部类
下一篇:c++删除数组中的某个元素
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站