在这种情况下如何使用动态多态?

时间:2014-04-23 19:19:33

标签: c++ inheritance coding-style polymorphism

我有以下简单的类来模拟点集。

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的指针。

当我添加更复杂的形状时,如何修改此代码以适应更多此类情况?

1 个答案:

答案 0 :(得分:1)

你可能想要MultiMethods。具体来说,您需要实际类型的运行时调度。

这是关于他们的帖子:"type-switch" construct in C++11

BTW:由于您始终将std::shared_ptrShape派生的所有对象一起使用,请考虑使用std::enable_shared_from_this

此外,您可能想要创建一个边界框并检查空交叉点。作为添加的优化,添加一个空形状(静态Singleton对象)。 Shape本身就是一个很好的类型。