gpt4 book ai didi

c++ - 不同形状之间的交集

转载 作者:行者123 更新时间:2023-11-30 02:57:32 25 4
gpt4 key购买 nike

我正在尝试制作一个形状库。有以下类 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 子类创建了一个成员函数。
看起来不错,但有一个问题。当您调用交集并给出一个形状(我的意思是编译器不知道它是什么形状,例如,当从形状 vector 中获取时)作为参数时,它不起作用(g++:没有匹配的调用函数)。
我想这是因为我没有覆盖 Shape 的虚函数,因为只要参数不同,函数就不同(我认为)。
好吧,我想知道是否有一种很酷的方法可以实现这个目标。

编辑:我在现代 c++ 设计的第 11 章中找到了更多关于我的问题的内容。它是关于多重方法(具有必须在运行时检查其类型的参数的方法)。在本章的第 9 节中,作者提到当与 static_cast 一起使用时,dynamic_cast 是一个不错的选择。如果我找到更多相关信息,我将再次编辑。
EDIT 2:在《Modern c++ design》第11章的第二节中,作者提到游戏中不同形状之间的碰撞检测是一个典型的问题,需要使用multimethods。我没说,但这个小图书馆本来是用来玩游戏的,所以它正是我要找的。

最佳答案

设计有误。第一个 Shape 需要一个名为 BoundingRect 的虚方法,它返回派生类填充区域的顶部、左侧、底部和右侧。然后 Shape.intersection 做的第一件事是确定边界矩形是否相交;一个简单的练习。

现在越来越难了。每个形状都必须提供一个虚拟名称 Paths,它返回真实描述该区域的线段/贝塞尔曲线的列表/数组。 intersection 方法然后确定任一形状中的任何路径是否相交。

祝你好运。

关于c++ - 不同形状之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com