将子类实例替换为超类引用c ++

时间:2013-12-04 02:19:20

标签: c++ inheritance polymorphism

class MovablePoint : public Point { 
   // MovablePoint is a subclass of Point
   // Something 
}
Point * ptrP1 = new MovablePoint(11, 12, 13, 14);

如果我得到上述格式,我可能知道在这种情况下我的指针ptrP1将指向Point类型的对象或MovablePoint类型的对象吗?

1 个答案:

答案 0 :(得分:0)

您可以使用dynamic_cast

MovablePoint* pMovPoint = dynamic_cast<MovablePoint*>(ptrP1);

如果可以转换,它将返回有效指针,否则将返回0.