C++_4种强制类型转换
C++的四种强制类型转换为:static_cast、const_cast、reinterpret_cast和dynamic_cast
类型转换的一般形式:cast-name<type>(expression);
任何具有明确定义的类型转换,只要不包含底层const,都可以使用static_cast;注: 顶层const:表示指针本身是个常量。如:int *const p; 底层const:表示指针所指的对象是一个常量。如:int const *p;
该运算符只能改变运算对象的底层const。
#include<iostream> using namespace std; int main() { const char *pc=" HDU"; char *p=const_cast<char *>(pc); cout<<"hello"<<p<<endl; return 0; }注:此处只能用const_cast,而不能用static_cast;
通常为运算对象的位模式提供较低层次上的重新解释。 注: 1、在指针之间转换,将一个类型的指针转换为另一个类型的指针,无关类型; 2、将指针值转换为一个整型数,但不能用于非指针类型的转换。
示例:
#include<iostream> using namespace std; int main() { int a=10; int *i=&a; long pc=reinterpret_cast<long>(i);//把一个指针转换为一个整数,即取出地址值 char *str=reinterpret_cast<char *>(i);//把int*转换为char *(比int型小),无输出 long *l=reinterpret_cast<long *>(i);//把int *转换为long *(比int型大),取出地址值(即i值)输出 cout<<*i<<endl; cout<<hex<<pc<<endl; cout<<i<<endl; cout<<"char:"<<str<<endl; cout<<l<<endl; return 0; }输出结果如下:
运行时类型识别(以区别以上三个均在编译时识别),用于将基类的指针或引用安全地转换成派生类的指针或引用。 对指针进行dynamic_cast,失败返回null,成功返回正常cast后的对象指针;
对引用进行dynamic_cast,失败抛出一个异常bad_cast,成功返回正常cast后的对象引用。
对于“向上转换”(即派生类指针或引用类型转换为其基类类型),无论是指针还是引用向上转换都是安全地。
对于“向下转型”有两种情况: 一种是基类指针所指对象是派生类类型的,这种转换是安全的; 另一种是基类指针所指对象为基类类型,在这种情况下dynamic_cast在运行时做检查,转换失败,返回结果为0;
在引用上,dynamic_cast依旧是常用于“安全的向下转型”。与指针一样,引用的向下转型也可以分为两种情况,与指针不同的是,并不存在空引用,所以引用的dynamic_cast检测失败时会抛出一个bad_cast异常。
示例如下:
#include<iostream> using namespace std; class Base { public: Base(){}; virtual void Show(){cout<<"This is Base calss";} }; class Derived:public Base { public: Derived(){}; void Show(){cout<<"This is Derived class";} }; int main() { //这是第一种情况 Base* base = new Derived; if(Derived *der= dynamic_cast<Derived*>(base)) { cout<<"第一种情况转换成功"<<endl; der->Show(); cout<<endl; } //这是第二种情况 Base * base1 = new Base; if(Derived *der1 = dynamic_cast<Derived*>(base1)) { cout<<"第二种情况转换成功"<<endl; der1->Show(); } else { cout<<"第二种情况转换失败"<<endl; } delete(base); delete(base1); return 0; }
运行结果如下:
总 结
去const属性用const_cast。
基本类型转换用static_cast。
多态类之间的类型转换用daynamic_cast。
不同类型的指针类型转换用reinterpreter_cast。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: C++11定义的数据类型
- 下一篇: dos批处理中的管道命令"|"有什么作用