本节介绍c++类型转换的相关知识。c++是强类型语言,存在一个类型系统用来将一种类型的数据强制转换成另一种类型。一般有两种方式进行强制类型转换。
- c风格类型转换
-
int a = 5;
double value = a;
double b = 8.4 + (int)value;
- c++风格类型的转换
-
static_cast:静态类型转换
-
reinterpret_cast:和类型双关类似,将一段内存解释成别的类型
-
dynamic_cast:动态类型转换
-
const_cast:移除或添加变量的const限定
-
上述四种类型转换均提供编译时检查功能,使用起来更加安全。
-
代码示例如下:
-
#include<iostream> class Base { public: Base(){} virtual ~Base(){} }; class Derived : public Base { public: Derived(/* args */){}; ~Derived(){}; }; class AnotherClass : public Base { public: AnotherClass(/* args */){}; ~AnotherClass(){}; }; int main() { double value = 4.3; //AnotherClass* s1 = static_cast<AnotherClass*>(&value); //使用static_cast进行类型转换,会检查类型,static_cast from 'double *' to 'AnotherClass *' is not allowed //要解决上述问题,需要使用reinterpret_cast AnotherClass* s = reinterpret_cast<AnotherClass*>(&value); //dynamic_cast:在做特定类型转换是提供一种安全机制,专门用于继承层次结构的强制类型转换。 Derived* dervied = new Derived(); Base* base = dervied; AnotherClass* ac = dynamic_cast<AnotherClass*>(base);//dynamic_cast转换会有返回值,可以检测转换是否成功 if (ac) { std::cout << "转换成功" << std::endl; } else { std::cout << "转换失败" << std::endl; //执行else分支,因为base在代码中是Derived类 } std::cin.get(); }