不同形状之间的交集
Intersection between different shapes
我正在尝试制作一个形状库。有以下类 Shape,具有以下声明:
#include "pos.h"
#ifndef SHAPE_H
#define SHAPE_H
class Shape{
protected:
Pos pos;
public:
Pos getPos();
void setPos(Pos pos);
virtual bool intersection(Shape&);
Shape():pos((Pos){0,0}){}
Shape(Pos pos):pos(pos){}
Shape(int x, int y):pos((Pos){x,y}){}
};
#endif /* SHAPE_H */
如您所见,有一个虚函数成员(交集)。此函数旨在计算两个形状是否相交(如果它们是圆形、矩形或其他形状,则不相交)。我还声明了这些类(圆形和矩形):
#include "pos.h"
#include "shape.h"
#ifndef RECTANGLE_H
class Rectangle;
#endif /* RECTANGLE_H */
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle : public Shape{
private:
int radius;
public:
int getRadius(){return radius;}
void setRadius(int radius){this->radius=radius;}
bool containsPos(Pos p);
bool intersection(Circle& c);
bool intersection(Rectangle& r);
Circle();
Circle(Pos pos);
Circle(int radius);
Circle(Pos pos, int radius);
};
#endif /* CIRCLE_H */
#include "pos.h"
#include "shape.h"
#ifndef CIRCLE_H
class Circle;
#endif /* CIRCLE_H */
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle : public Shape{
private:
int width;
int height;
public:
int getWidth(){return width;}
int getHeight(){return height;}
void setWidth(int width){this->width=width;}
void setHeight(int height){this->height=height;}
bool containsPos(Pos pos);
bool intersection(Rectangle& r);
bool intersection(Circle& c);
Rectangle():Shape(),width(0),height(0){}
Rectangle(int w, int h):Shape(),width(w),height(h){}
Rectangle(Pos p, int w, int h):Shape(p), width(w),height(h){}
Rectangle(int x, int y, int w, int h):Shape(x,y), width(w), height(h){}
};
#endif /* RECTANGLE_H */
如您所见,我在 Shape 的每个子类中为 Shape 的每个其他子类创建了一个成员函数。
看起来不错,但有一个问题。当你调用交集给出一个形状(我的意思是编译器不知道它是形状,例如当从形状向量中获取时)作为参数时,它不起作用(g++:没有匹配函数用于调用)。
我想这是因为我没有覆盖 Shape 的虚函数,因为只要参数不同,函数就不同(我认为)。
好吧,我想知道是否有一种很酷的方法来实现这个目标。
编辑:我在现代c ++设计的第11章中找到了更多关于我的问题的东西。它是关于多方法(带有参数的方法,其类型必须在运行时检查)。在本章第9节中,作者提到,当static_cast被说服时,dynamic_cast是一个不错的选择。如果我找到更多关于此的信息,我将再次编辑。
编辑2:在"现代C ++设计"的第11章中,您可以在第二节中找到作者提到游戏中不同形状之间的碰撞检测是需要使用多方法的典型问题。我没有说,但这个小库是用来玩游戏的,所以这正是我想要的。
设计是错误的。 First Shape 需要一个名为 BoundingRect
的虚拟方法,该方法返回派生类填充区域的"上"、"左"、"下"、"右"。然后 Shape.intersection 做的第一件事是确定边界矩形是否相交;一个微不足道的练习。
现在它变得更难了。 每个形状都必须提供一个虚拟名称Paths
,它返回一个真正描述该区域的线段/贝塞尔曲线的列表/数组。 然后,intersection
方法确定任一形状中的任何路径是否相交。
祝你好运。
启用运行时类型信息,创建一个实际采用 Shape 类的交集方法,并使用dynamic_cast找出你得到的对象,然后对派生对象调用重载的交集调用。
请注意,RTTI 会严重减慢代码速度,并且为每种类型的形状提供特殊功能会严重阻碍代码的灵活性和可维护性。从长远来看,像理查德提出的广义解决方案可能更有益。
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 构造函数和转换运算符之间的重载解析
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数