1) 定义一个矩形(Rectangle)类,该类代表了一个矩形。可以定义不同的矩形,并对矩形进行如下运算:
移动矩形
判断一个点是否在矩形内部
求两个矩形合并后的矩形,通过函数返回值返回代表合并后矩形的新建立
的矩形对象
求两个矩形交集,通过函数返回值返回代表两个矩形交集的一个新建立的
矩形对象
.
点不在矩形内部 合并后的矩形 两个矩形的交集
设计提示
矩形类提示如下:
(1) 左上角坐标(x, y,)和矩形的宽度width、高度height可以描绘一个矩形
。
(2) 由于要判断点是否在矩形内,所以判断函数(isInside)应该作为该类的方
法,同样合并矩形(unionWith)和求两个矩形的交集(intersection)也分
别是方法。
(3) 可以定义多个构造函数,第一个是无参构造函数Rectangle,此时默认为
左上角和右下角的坐标都是(0,0),实际是一个点。第二个有4个参数Rect
angle (double x, double y, double width, double height),分别代表左上
角坐标、宽度和高度。第三个有两个参数Rect(double width, double heigh
t),认为左上角和右下角坐标分别是(0,0)和(width, height)。
测试代码提示如下:
(1) 定义多个矩形对象和点坐标变量
(2) 调用对象方法isInside判断一个点是否在矩形内并打印合并后的结果
(3) 调用unionWith合并矩形并打印合并后的结果
(4) 调用intersection求矩形的交集并打印合并后的结果
// Q764632.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
class Rectangle
{
public:
int l;
int t;
int r;
int b;
Rectangle() { l = t = r = b = 0; }
Rectangle(const Rectangle& rect)
{
l = rect.l;
t = rect.t;
r = rect.r;
b = rect.b;
}
Rectangle(int left, int top, int width, int height)
{
l = left;
t = top;
r = l + width;
b = t + height;
}
void move(int x, int y)
{
l += x;
r += x;
t += y;
b += y;
}
int isInside(int x, int y)
{
return (x > l) && (x < r) && (y > t) && (y < b);
}
Rectangle unionWith(Rectangle rect)
{
Rectangle re;
re.l = l > rect.l ? rect.l : l;
re.r = r > rect.r ? r : rect.r;
re.t = t > rect.t ? rect.t : t;
re.b = b > rect.b ? b : rect.b;
return re;
}
Rectangle intersection(Rectangle rect)
{
Rectangle re;
re.l = l < rect.l ? rect.l : l;
re.r = r < rect.r ? r : rect.r;
re.t = t < rect.t ? rect.t : t;
re.b = b < rect.b ? b : rect.b;
return re;
}
void PrintRect()
{
cout << "left=" << l << ",top=" << t << ",width=" << r - l << ",height=" << b - t << endl;
}
};
int main()
{
//(1) 定义多个矩形对象和点坐标变量
Rectangle r1(10, 10, 10, 10), r2(5, 5, 10, 10), r3(20, 20, 15, 5);
r1.PrintRect();
r2.PrintRect();
r3.move(5, -5);
r3.PrintRect();
//(2) 调用对象方法isInside判断一个点是否在矩形内并打印合并后的结果
cout << r1.isInside(15, 15) << endl;
cout << r1.isInside(5, 5) << endl;
//(3) 调用unionWith合并矩形并打印合并后的结果
Rectangle r4 = r1.unionWith(r3);
r4.PrintRect();
//(4) 调用intersection求矩形的交集并打印合并后的结果
Rectangle r5 = r1.intersection(r2);
r5.PrintRect();
}