C++4种类型转换

总 结

  去const属性用const_cast。

  基本类型转换用static_cast。

  多态类之间的类型转换用daynamic_cast。

  不同类型的指针类型转换用reinterpreter_cast。

static_cast

任何具有明确定义的类型转换,只要不包含底层const,都可以使用static_cast;

注:

顶层const:表示指针本身是个常量。如:int *const p;

底层const:表示指针所指的对象是一个常量。如:int const *p;

const_cast

该运算符只能改变运算对象的底层const。

[cpp] view plain copy

  1. #include<iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     const char *pc=" HDU";  
  8.     char *p=const_cast<char *>(pc);  
  9.   
  10.     cout<<"hello"<<p<<endl;  
  11.   
  12.     return 0;  
  13. }  

注:此处只能用const_cast,而不能用static_cast;

reinterpret_cast

通常为运算对象的位模式提供较低层次上的重新解释。

注:

1、在指针之间转换,将一个类型的指针转换为另一个类型的指针,无关类型;

2、将指针值转换为一个整型数,但不能用于非指针类型的转换。

示例: 

[cpp] view plain copy

  1. #include<iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     int a=10;  
  8.     int *i=&a;  
  9.     long pc=reinterpret_cast<long>(i);//把一个指针转换为一个整数,即取出地址值  
  10.     char *str=reinterpret_cast<char *>(i);//把int*转换为char *(比int型小),无输出  
  11.     long *l=reinterpret_cast<long *>(i);//把int *转换为long *(比int型大),取出地址值(即i值)输出  
  12.   
  13.     cout<<*i<<endl;  
  14.     cout<<hex<<pc<<endl;  
  15.     cout<<i<<endl;  
  16.     cout<<"char:"<<str<<endl;  
  17.     cout<<l<<endl;  
  18.   
  19.     return 0;  
  20. }  

输出结果如下:

dynamic_cast

运行时类型识别(以区别以上三个均在编译时识别),用于将基类的指针或引用安全地转换成派生类的指针或引用。

对指针进行dynamic_cast,失败返回null,成功返回正常cast后的对象指针; 
对引用进行dynamic_cast,失败抛出一个异常bad_cast,成功返回正常cast后的对象引用。 

对于“向上转换”(即派生类指针或引用类型转换为其基类类型),无论是指针还是引用向上转换都是安全地。

对于“向下转型”有两种情况:

一种是基类指针所指对象是派生类类型的,这种转换是安全的;

另一种是基类指针所指对象为基类类型,在这种情况下dynamic_cast在运行时做检查,转换失败,返回结果为0;

在引用上,dynamic_cast依旧是常用于“安全的向下转型”。与指针一样,引用的向下转型也可以分为两种情况,与指针不同的是,并不存在空引用,所以引用的dynamic_cast检测失败时会抛出一个bad_cast异常。

示例如下:

[cpp] view plain copy

  1. #include<iostream>  
  2.   
  3. using namespace std;  
  4. class Base  
  5. {  
  6. public:  
  7.   Base(){};  
  8.   virtual void Show(){cout<<"This is Base calss";}  
  9. };  
  10. class Derived:public Base  
  11. {  
  12. public:  
  13.   Derived(){};  
  14.   void Show(){cout<<"This is Derived class";}  
  15. };  
  16. int main()  
  17. {  
  18.     //这是第一种情况  
  19.     Base* base = new Derived;  
  20.     if(Derived *der= dynamic_cast<Derived*>(base))  
  21.     {  
  22.         cout<<"第一种情况转换成功"<<endl;  
  23.         der->Show();  
  24.         cout<<endl;  
  25.     }  
  26.     //这是第二种情况  
  27.     Base * base1 = new Base;  
  28.     if(Derived *der1 = dynamic_cast<Derived*>(base1))  
  29.     {  
  30.         cout<<"第二种情况转换成功"<<endl;  
  31.         der1->Show();  
  32.     }  
  33.     else  
  34.     {  
  35.         cout<<"第二种情况转换失败"<<endl;  
  36.     }  
  37.     delete(base);  
  38.     delete(base1);  
  39.   
  40.     return 0;  
  41. }  

运行结果如下:

猜你喜欢

转载自blog.csdn.net/weixin_41066529/article/details/90175105
今日推荐