// C++ Cast 示例
#include <iostream>
using namespace std;
int main() {
// 1. static_cast: 用于基本类型之间的转换,如 int 到 float
int a = 10;
float b = static_cast<float>(a) / 3; // 将 int 转换为 float
cout << "static_cast example: " << b << endl;
// 2. dynamic_cast: 主要用于类层次结构中的安全向下转型
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
void sayHello() {
cout << "Hello from Derived" << endl;
}
};
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
derivedPtr->sayHello(); // 安全地调用派生类的方法
} else {
cout << "dynamic_cast failed" << endl;
}
// 3. const_cast: 用于移除或添加 const 属性
const int c = 20;
int* nonConstPtr = const_cast<int*>(&c); // 移除 const 属性
*nonConstPtr = 30; // 修改原来的 const 变量(不推荐)
cout << "const_cast example: " << c << endl;
// 4. reinterpret_cast: 用于低级别的重新解释指针或整数
int d = 42;
void* voidPtr = reinterpret_cast<void*>(&d); // 将 int 指针转换为 void 指针
cout << "reinterpret_cast example: " << voidPtr << endl;
return 0;
}
static_cast:用于基本类型的转换,例如将 int 转换为 float。它不会进行运行时检查。dynamic_cast:用于类层次结构中的安全向下转型。它会在运行时检查转换的有效性,如果转换失败会返回 nullptr 或抛出异常。const_cast:用于移除或添加 const 属性。它可以用来修改 const 变量的值,但这通常被认为是不安全的操作。reinterpret_cast:用于低级别的重新解释指针或整数。它不会进行任何类型的检查,直接在内存级别上进行转换,因此非常危险,应谨慎使用。希望这些示例和解释对你有帮助!
上一篇:c++ return
下一篇:c++ 算法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站