dynamic_cast的试用(指针、引用)
1 #include<iostream> 2 #include<stdexcept> 3 using namespace std; 4 5 class A{ 6 public: 7 A(int a):val(a){ 8 //empty 9 } 10 virtual void print(){ 11 cout<<"A-print"<<endl; 12 } 13 void nonvirtual(){ 14 cout<<"A-nonvirtual"<<endl; 15 } 16 void printVal(){ 17 cout<<val<<endl; 18 } 19 private: 20 int val; 21 }; 22 23 class B:public A{ 24 public: 25 B(int a):val(a),A(3){//derived object是会调用base的constructor的,别忘了 26 //empty 27 } 28 void print(){ 29 cout<<"B-print"<<endl; 30 } 31 void nonvirtual(){ 32 cout<<"B-nonvirtual"<<endl; 33 } 34 void printVal(){ 35 cout<<val<<endl; 36 } 37 private: 38 int val; 39 }; 40 41 void test(B* bPtr){ 42 cout<<"success"<<endl; 43 } 44 45 int main(){ 46 A aTest(1); 47 B bTest(2); 48 A *aPtr=&bTest; 49 B *bPtr1,*bPtr2; 50 51 //测试dynamic_cast完成后被转化的指针有没有改动 52 aPtr->printVal(); 53 //test(aPtr);//error :类型不匹配 54 test(dynamic_cast<B*>(aPtr)); 55 bPtr1=dynamic_cast<B*>(aPtr); 56 aPtr->printVal();//先后aPtr都没有变过,说类型转换是指返回了想要的类型 57 bPtr1->printVal(); //完成了类型转换 58 cout<<"**********************"<<endl; 59 60 //各种能不能转换成功的条件测试 61 //要转换的指针是基类并指向基类 【失败】 62 aPtr=&aTest; 63 aPtr->printVal(); 64 bPtr2=dynamic_cast<B*>(aPtr); 65 if(bPtr2==0) cout<<"fail"<<endl;//如果转换失败,会返回0,所以要记得查验 66 cout<<"***********************"<<endl; 67 68 //要转换的是基类引用,该reference引用了基类对象 【失败】 69 A &aRef=aTest; 70 B &bRef=dynamic_cast<B&>(aRef); //引用一定要在定义的时候就初始化别忘了 71 //error:terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast 72 bRef.printVal(); 73 }
什么能够情况下转换成功:
1)e的类型是目标type的public派生类:派生类向基类转换一定会成功。
2)e的类型是目标type的基类,当e是指针指向派生类对象,或者基类引用引用派生类对象时,类型转换才会成功,当e指向基类对象,试图转换为派生类对象时,转换失败。
3)e的类型就是type的类型时,一定会转换成功。
————————————————
最后这段总结来自CSDN博主「sky0942」的原创文章,原文链接:https://blog.csdn.net/xingkongfenqi/article/details/49148885
Look, if you had one shot , one opportunity , to seize everything you ever wanted , in one moment.
Would you captrue it , or just let it slip ?

浙公网安备 33010602011771号