dymanic_cast一点点点点补充
感谢CSDN博主「sky0942」关于dynamic_cast的整理(https://blog.csdn.net/xingkongfenqi/article/details/49148885),让我理清了很多概念。
原文提到:
(dynamic_cast<type*>(e)//e为指针 或者 dynamic_cast<type&>(e)//e为左值 或者 dynamic_cast<type&&>(e)//e为右值)
e能成功转换为type型的情况有三种:
1)e的类型是目标type的公有派生类:派生类向基类转换一定会成功。
2)e的类型是目标type的基类,当e是指针指向派生类对象,或者基类引用引用派生类对象时,类型转换才会成功,当e指向基类对象,试图转换为派生类对象时,转换失败。
3)e的类型就是type的类型时,一定会转换成功。
我再对(2)做一点点点点理解:
e的类型是目标type的基类,当e是指针,指向的派生类对象应该就只能是目标type,不能是其他派生类,类型转换才会成功。
测试如下:
1 #include<iostream> 2 using namespace std; 3 class A{ 4 public: 5 virtual void print(int){ 6 cout<<"A-print"<<endl; 7 } 8 }; 9 class B:public A{ 10 public: 11 void print(){ 12 cout<<"B-print"<<endl; 13 } 14 }; 15 class C:public A{ 16 void print(){ 17 cout<<"C-prind"<<endl; 18 } 19 }; 20 int main(){ 21 //B、C都是A的派生类 22 //现在尝试把分别指向B、C的A类指针转换为B类指针 23 //目标type是B,基类是A 24 B bTest,*bPtr1,*bPtr2; 25 C cTest; 26 A aTest; 27 A *aPtr1,*aPtr2; 28 aPtr1=&bTest; 29 aPtr2=&cTest; 30 31 bPtr1=dynamic_cast<B*>(aPtr1); 32 bPtr2=dynamic_cast<B*>(aPtr2); 33 34 if(bPtr1==0) cout<<"fail to convert aPtr1(aim at B) to B-type pointer"<<endl;//转换成功 35 else cout<<"success to convert aPtr1(aim at B) to B-type pointer"<<endl; 36 if(bPtr2==0) cout<<"fail to convert aPtr2(aim at C) to B-type pointer"<<endl;//转换失败 37 else cout<<"success to convert aPtr2(aim at C) to B-type pointer"<<endl; 38 }
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号