-1

我在弄清楚程序的这一部分时遇到问题:

编写一个非成员函数,intersection(),它接受两个 Rectangle 参数并返回一个包含两者交集的 Rectangle。当然,如果两个 Rectangle 不相交,它应该返回默认的 Rectangle。

到目前为止,这是我的 .cpp 代码:

Rectangle::Rectangle()
{
    p1.x = 0;
    p1.y = 0;
    p2.x = 0;
    p2.y = 0;
}
Rectangle::Rectangle(double x, double y, double width, double height)
{
    p1.x = x;
    p1.y = y;
    p2.x = x + width;
    p2.y = y + height;
}
double Rectangle::getArea() const
{
    return (p2.x - p1.x) * (p2.y - p1.y);
}
double Rectangle::getWidth() const
{
    return (p2.x - p1.x);
}
double Rectangle::getHeight() const
{
    return (p2.y - p1.y);
}
double Rectangle::getX() const
{
    return p1.x;
}
double Rectangle::getY() const
{
    return p1.y;
}
void Rectangle::setLocation(double x, double y)
{
    p1.x = x;
    p1.y = y;
}
void Rectangle::setSize(double width, double height)
{
    p2.x = width;
    p2.y = height;
}

Rectangle intersection(const Rectangle& rec1, const Rectangle& rec2)
{
    double ix = 0.0;
    double iy = 0.0;
    double iwidth = 0.0;
    double iheight = 0.0;

    if(rec1.getX() > rec2.getX() && rec2.getX() > (rec1.getX() + rec1.getWidth()) 
        && rec1.getY() > rec2.getY() && rec2.getY() > (rec1.getY() + rec1.getHeight()))
    {
        ix = rec2.getX();
        iy = rec2.getY();
        iwidth = rec1.getX() + rec1.getWidth();
        iheight = rec1.getY() + rec1.getHeight();
    }

我没有写“else”部分,因为首先,这个“if 语句应该在某些情况下检查正确,但没有;我假设 (0, 0) 在左下角,因为我已经尝试过了(0, 0) 在左上角并且不起作用

4

1 回答 1

3

Consider intersection of rectangles as intersection of 2 pairs of intervals:

First pair is intersection of horizontal sides of rectangles:

Intersection1 = (rec1.getX(), rec1.getX()+rec1.getWidth())&(rec2.getX(), rec2.getX()+rec2.getWidth())

Second pair is intersection of vertical sides of rectangles:

Intersection2 = (rec1.getY(), rec1.getY()+rec1.getHeight())&(rec2.getY(), rec2.getY()+rec2.getHeight())

If both of these intersections are not empty - then you can make a result intersection rectangle which sides are these intersections.

All you need to do is to properly implement interval intersection function.

于 2013-10-21T18:04:04.283 回答