1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| class Shape { public: virtual ~Shape() = default; float getX() const; float getY() const; virtual void accept(ShapeVisitor &) = 0; protected: Shape(float x, float y); private: ... };
class Square : public Shape { public: Square(float x, float y, float width, float height); float getArea() const; float getHeight() const; float getWidth() const; void accept(ShapeVisitor & visitor) override { visitor.visitShape(*this); } private: ... };
class Circle : public Shape { public: Circle(float x, float y, float radius); float getArea() const; float getRadius() const; void accept(ShapeVisitor & visitor) override { visitor.visitShape(*this); } private: ... };
class ShapeVisitor { public: virtual ~ShapeVisitor() = default; virtual void visitShape(const Circle &) = 0; virtual void visitShape(const Square &) = 0;
};
void BoundingBoxCalculator::visitShape(const Circle & circle) { const float x = circle.getX(); const float y = circle.getY(); const float radius = circle.getRadius();
bottom = std::max(bottom, y + radius); left = std::min(left, x - radius); right = std::max(right, x + radius); top = std::min(top, y - radius); } void ShapePrinter::visitShape(const Square & square) { std::cout << "Square " << "{ x: " << square.getX() << ", y: " << square.getY() << ", width: " << square.getWidth() << ", height: " << square.getHeight() << " } " << std::endl; }
int main() { std::vector<std::shared_ptr<Shape>> shapes; shapes.push_back(std::make_shared<Circle>(-1.f, 2.f, 0.5f)); shapes.push_back(std::make_shared<Square>(12.f, 3.f, 1.2f, 3.4f));
BoundingBoxCalculator calculator; for (auto shape : shapes) { shape->accept(calculator); } }
|