应用场景:
多态中基类指针或应用转换为子类的指针或引用。
必要条件,缺一不可:
1,必须是多态的场景,即基类中有虚函数。(若没有虚函数,则编译不过)
2,基类指针或引用确实指向了子类的对象。(若基类不确实指向子类,则转换失败,dynamic_cast返回nullptr)
#include <iostream>
using namespace std;
class Shape{
public:
Shape(int x,int y)
:_x(x),_y(y){}
virtual void draw()
{
cout<<"draw Shap ";
cout<<"start ("<<_x<<","<<_y<<") "<<endl;
}
protected:
int _x;
int _y;
};
class Circle: public Shape
{
public:
Circle(int x, int y,int r)
:Shape(x,y),_r(r){}
void draw()
{
cout<<"draw Circle ";
cout<<"start ("<<_x<<","<<_y<<") ";
cout<<"raduis r = "<<_r<<endl;
}
private:
int _r;
};
int main()
{
Shape s(3,5);
Circle c(1,2,4);
Shape *ps = &c;
Circle * pc = dynamic_cast<Circle*>(ps);
if(pc == nullptr){
cout<<"pc is nullptr"<<endl;
return 0;
}
pc->draw();
return 0;
}