#include <iostream>
using namespace std;
int main() {
// 静态类型转换 (static_cast)
double d = 10.5;
int i = static_cast<int>(d); // 将double转换为int,结果为10
cout << "static_cast: " << i << endl;
// 动态类型转换 (dynamic_cast),主要用于类层次结构中的指针或引用的向下转型
class Base {};
class Derived : public Base {};
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // 安全地将Base*转换为Derived*
if (derivedPtr) {
cout << "dynamic_cast: successful cast" << endl;
} else {
cout << "dynamic_cast: failed cast" << endl;
}
// 常量类型转换 (const_cast)
const int constValue = 20;
int* nonConstPtr = const_cast<int*>(&constValue); // 移除const属性
*nonConstPtr = 30; // 修改值(不推荐,因为constValue仍然是const)
cout << "const_cast: " << *nonConstPtr << endl;
// 重解释类型转换 (reinterpret_cast),用于低级别的类型转换
int intValue = 42;
void* voidPtr = reinterpret_cast<void*>(intValue); // 将int重新解释为void*
cout << "reinterpret_cast: " << voidPtr << endl;
return 0;
}
静态类型转换 (static_cast):
double 转换为 int。动态类型转换 (dynamic_cast):
nullptr 或抛出异常(对于引用类型)。常量类型转换 (const_cast):
const 或 volatile 属性。const 的对象会导致未定义行为。重解释类型转换 (reinterpret_cast):
上一篇:c++rand函数
下一篇:c++输出字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站