
int 转换为 float,或指针转换为 void*。static_cast。static_cast,但不能通过虚拟继承转换,且不进行运行时检查,若目标类型并非对象实际类型会导致未定义行为。示例:
static_cast<float>(1); // 将整数 1 显式转换为浮点数 1.0const 属性,这是其他 C++ 类型转换操作符无法做到的,也适用于 volatile 属性。const 重载成员函数时很有用,但修改原本为 const 的值是未定义行为,除非原始变量本身不是 const。示例:
const int num = 5;
int& nonConstNum = const_cast<int&>(num); nullptr。std::bad_cast 异常。示例:
class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Base* b = new Derived;
Derived* d = dynamic_cast<Derived*>(b);
if (d!= nullptr) {
d->show(); // 转换成功,输出 "Derived class"
} else {
std::cout << "Conversion failed" << std::endl;
}
delete b;
return 0;
}int 中。std::bit_cast 是更好选择。示例:
int num = 10;
double* ptr = reinterpret_cast<double*>(&num); <bit> 头文件中。memcpy 实现类似功能。示例:
#include <bit>
struct S1 {
int a;
float b;
};
struct S2 {
int c;
float d;
};
S1 s1 = {1, 2.0f};
S2 s2 = std::bit_cast<S2>(s1); static_cast<int>(x))在代码中的可识别性高于 C 风格的强制类型转换(如 (int)x),有助于代码阅读和维护,使开发者更快理解代码意图。dynamic_cast 在运行时检查转换有效性:nullptr。const_cast 专门用于修改 const 或 volatile 属性,C 风格强制类型转换无法实现此功能,可减少类型转换错误。class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Base* b = new Derived;
Derived* d = dynamic_cast<Derived*>(b);
if (d!= nullptr) {
d->show(); // 转换成功,输出 "Derived class"
} else {
std::cout << "Conversion failed" << std::endl;
}
delete b;
return 0;
}dynamic_cast 将基类指针 b 转换为派生类指针 d,由于 b 指向 Derived 类对象,转换成功,避免了非法访问。class Base {
public:
void show() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void show() {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Base* b = new Base;
Derived* d = (Derived*)b; // C 风格强制类型转换
d->show(); // 未定义行为,可能导致程序崩溃
delete b;
return 0;
}Base 类指针 b 转换为 Derived 类指针 d,但 b 实际指向 Base 类对象,会导致未定义行为和程序崩溃。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。