類型轉換一 dynamic_cast
在繼承體系中安全的向下轉型,如果指針類型轉型失敗返回一個空指針,如果是引用則拋出一個異常
#include <iostream>
using namespace std;
class A
{
virtual void fun(){}
};
class B:public A
{
public:
void fun(){}
void print()
{
cout<<"Derived"<<endl;
}
};
int main()
{
B *b=nullptr;
A *a=new A();
b=dynamic_cast<B *>(a);
b==nullptr?cout<<"error":cout<<"yes";
cout<<endl;
A *a1=new B();
b=dynamic_cast<B *>(a1);
b==nullptr?cout<<"error":cout<<"yes";
cout<<endl;
b->print();
cout<<endl;
}