C++-几何基元类层次结构

C++ - geometric primitives class hierarchy

本文关键字:层次结构 何基元 C++-      更新时间:2023-10-16

我是C++的新手,我想学习我的第一个教程。

我想写一个程序,它将实现对表示图形符号的对象列表的搜索。

该列表包含由两个边长描述的矩形和由半径描述的圆。

我还想创建一个搜索过程,它接受一个列表和矩形的边长,并返回另一个列表,其中只包含这些适合给定矩形的符号。

列表(和搜索功能)的实现应允许在不修改的情况下扩展已接受符号的列表(例如添加多边形)任何现有代码。

我应该采取什么样的方法?你能给我举一个与我的目标相似的例子吗?

这是多态性的一种用法-您将使用std::vector<Object*>std::vector<std::shared_ptr<Object>>来保存对象列表。

对象本质上应该是这样的:

class Object
{
public:
    virtual ~Object() = default;
    // needs to be implemented by deriving classes i.e. Rectangle and Circle
    virtual bool fitsIn(Rectangle const& r) const = 0;
};

当然,RectangleCircle将从中继承:

class Rectangle : public Object
{
    int x, y, w, h;
public:
    Rectangle(int x, int y, int w, int h) : x(x), y(y), w(w), h(h) {}
    virtual bool fitsIn(Rectangle const& r) const override
    {
        // return whether can fit in r based on this object's and r's x, y, w and h
    }
};

然后,您可以将其添加到列表中,对每个元素进行迭代并调用fitsIn,根据fitsIn返回的内容将其推送到另一个向量:

std::vector<std::shared_ptr<Object>> objects, fitting_objects;
objects.push_back(new Rectangle(10, 10, 20, 20)); // classic polymorphism spectacle
// rectangle for the area containing the objects we're looking for
Rectangle r(5, 5, 30, 30);
for(auto const& object : objects)
    if(object.fitsIn(r))
        fitting_objects.push_back(object);