我正在使用 ptr_vector 来存储“形状”。我试图用派生的形状类填充它,例如“圆圈”,每次我尝试向下转换它们时,我都会得到糟糕的演员表。
class Shape
{
public:
virtual ~Shape() {};
virtual void print() { std::cout << "shape" << std::endl; };
};
class Circle :
public Shape
{
public:
void print() { std::cout << "circle" << std::endl; };
};
int main()
{
boost::ptr_vector<Shape> shapes;
shapes.push_back(new Circle);
BOOST_FOREACH(Shape shape, shapes)
{
Circle& tempCircle = dynamic_cast<Circle&>(shape);
if(&tempCircle != NULL)
tempCircle.print();
}
system("PAUSE");
}