1、设计一个名为Rectangle2D的类,表示平面坐标下的一个矩形,这个类包括:
四个double型数据成员:x, y, width, height,分别表示矩形中心坐标、宽和高
一个不带形参的构造函数,用于创建缺省矩形:(x,y)=(0,0), width=height=1
一个带形参的构造函数:Rectangle2D(double x, double y, double width, double height)
成员函数doublegetAera(),返回矩形面积
成员函数boolcontains(double x, double y),当给定点(x,y)在矩形内时返回true,否则返回
false,如下图a)
成员函数boolcontains(const Rectangle2D & r),当给定矩形在当前矩形内时返回true,否则
返回false,如下图b)
成员函数booloverlaps(const Rectangle2D & r),当给定矩形与当前矩形有重叠时返回true,
否则返回false,如下图c)
实现这个类,并在主函数中测试:创建r1(2,2,5.4,4.8),r2(4,5,10.6,3.3) 和r3(3,5,2.2,5.5),
输出r1的面积,以及r1.contains(3,3),r1.contains(r2) 和r1.overlaps(r3)的结果。
#include <iostream>
#include <cmath>
using namespace std;
class Rectangle2D
{
public:
Rectangle2D() : x(0.0), y(0.0), width(1.0), height(1.0) {};
Rectangle2D(double x, double y, double width, double height);
double getArea();
bool contains(double x, double y);
bool contains(const Rectangle2D & r);
bool overlaps(const Rectangle2D & r);
private:
double x, y, width, height;
};
Rectangle2D::Rectangle2D(double x, double y, double width, double height){
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
double Rectangle2D::getArea(){
return width * height;
}
bool Rectangle2D::contains(double x, double y){
return (x >= this->x && x <= this->x + this->width && y >= this->y && y <= this->y + this->height);
}
bool Rectangle2D::contains(const Rectangle2D &r) {
return fabs(r.x - x) <= (width - r.width) / 2 && fabs(r.y - y) <= (height - r.height) / 2;
}
bool Rectangle2D::overlaps(const Rectangle2D & r) {
return fabs(x - r.x) < (width + r.width) / 2 && fabs(y - r.y) < (height + r.height) / 2;
};
int main()
{
// 创建三个矩形
Rectangle2D r1(2, 2, 5.4, 4.8);
Rectangle2D r2(4, 5, 10.6, 3.3);
Rectangle2D r3(3, 5, 2.2, 5.5);
// 输出r1的面积
cout << "r1's area: " << r1.getArea() << endl;
// 测试contains和overlaps函数
cout << "r1.contains(3, 3): " << r1.contains(3, 3) << endl;
cout << "r1.contains(r2): " << r1.contains(r2) << endl;
cout << "r1.overlaps(r3): " << r1.overlaps(r3) << endl;
return 0;
}
Post Views: 3