C++-几何基元类层次结构
C++ - geometric primitives class hierarchy
我是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;
};
当然,Rectangle
和Circle
将从中继承:
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);
相关文章:
- 如何重构类层次结构以避免菱形问题
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 实现有界基元类型的c++
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++ 中模板化类型的类层次结构
- C++中的基元类型有析构函数吗?
- 初始化派生结构的基部分/意外打包派生结构字段以对齐基结构的间隙
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- C++具有基元类型的并发队列
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 抽象基类和层次结构-C++
- CRTP层次结构类的非模板基类
- 类层次结构设计,避免从基类到派生类的向下转换
- 在 C++ 的异常层次结构中引入其他基类型
- 返回基元类型和结构的本地对象
- C++-几何基元类层次结构
- 是否可以为模板化的基类提供专门的类层次结构,但仍利用它们之间的多态性
- 结构初始化(用户定义的类型和基元)
- 在结构/类中查找第一个基础基元
- 调用模板虚类层次结构中的基类方法