【发布时间】:2014-04-23 19:19:33
【问题描述】:
我有以下简单的类来模拟点集。
struct Shape
{
virtual bool contains(point x) const = 0;
}
typedef std::shared_ptr<Shape> ShapePtr;
struct Intersection : public Shape
{
Intersection(ShapePtr shape1, ShapePtr shape2):
shape1_(shape1),shape2_(shape2){}
ShapePtr shape1_;
ShapePtr shape2_;
bool contains(point x) const {return shape1_->contains(x) &&
shape2_->contains(x);}
}
ShapePtr intersect(ShapePtr shape1, ShapePtr shape2)
{
return std::make_shared<Intersection>(shape1, shape2);
}
到目前为止一切顺利。但是假设我添加了一个Shape,即Rectangle:
struct Rectangle : public Shape
{
double x1_,x2_,y1_,y2_;
...
}
原始代码运行良好,但可以利用两个矩形的交点是一个矩形这一事实来改进它。也就是说,intersect 函数可以返回一个指向Rectangle 的指针。
当我添加更复杂的形状时,我应该如何修改此代码以适应更多此类情况?
【问题讨论】:
标签: c++ inheritance coding-style polymorphism