定义一个RectangleList类,要求能够用于保存N个Rectangle类。
Rectangle的类:可以根据左下角坐标(x, y)以及宽(w)和高(h)构成一块封闭矩形区域,此外要求:
①Rectangle类需要包含成员函数intisLocated(),用来判断点(a, b)在上述构成的矩形内,矩形上还是矩形外(在矩形内返回1,矩形上返回0,矩形外返回-1);
②Rectangle类需要包含成员函数intcalPerimeter(),用来输出矩形的周长;
③Rectangle类需要包含成员函数intcalArea(),用来输出矩形的面积;
代码实现:
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
class Rectangle
{
public:
Rectangle(int a, int b, int c, int d) :x(a), y(b), w(c), h(d) {};
Rectangle(int a, int b, int c) :x(a), y(b), w(c), h(c) {};
Rectangle(int a, int b)
{
x = a; y = b; w = 1; h = 1;
}
Rectangle()
{
x = 0; y = 0; w = 1; h = 1;
}
void show()
{
cout << "x=" << x << ",y=" << y << ",w=" << w << ",h=" << h << endl;
}
int x;
int y;
int w;
int h;
};
class RectangleList
{
public:
Rectangle *p=new Rectangle[N];
int N;
RectangleList(int num)
{
N = num;
}
int i,j;
void showAll()
{
for (i = 0; i < N; i++)
p[i].show();
}
bool isCollide()
{
int boolean = 0;
for(i=0;i<N;i++)
for (j = 1; i + j < N; j++)
{
if (p[i].x <= p[i].x&&p[i].y >= p[i + j].y)
if ((p[i].x + p[i].w) > p[i+j].x && (p[i+j].y + p[i+j].h) > p[i].y)
boolean = 1;
if (p[i].x >= p[i+j].x&&p[i].y >= p[i+j].y)
if ((p[i+j].x + p[i+j].w) > p[i].x && (p[i+j].y + p[i+j].h) > p[i].y)
boolean = 1;
if (p[i].x <= p[i+j].x&&p[i].y <= p[i+j].y)
if ((p[i].x + p[i].w) > p[i+j].x && (p[i].y + p[i].h) > p[i+j].y)
boolean = 1;
if (p[i].x >= p[i+j].x&&p[i].y <= p[i+j].y)
if ((p[i+j].x + p[i].w) > p[i].x && (p[i].y + p[i].h) > p[i+j].y)
boolean = 1;
}
return(boolean);
}
~RectangleList()
{
cout << "RectangleList Deconstruct.";
}
};
Rectangle initRectangle(int paramNum)
{
int a, b, c, d;
if (paramNum == 4)
{
cin >> a >> b >> c >> d;
return(Rectangle(a, b, c, d));
}
if (paramNum == 3)
{
cin >> a >> b >> c;
return(Rectangle(a, b, c));
}
if (paramNum == 2)
{
cin >> a >> b;
return(Rectangle(a, b));
}
if (paramNum == 0)
{
return(Rectangle());
}
}
int main(){
int N;
cin>>N;
RectangleList l(N);
for(int i=0;i<N;i++){
int paramNum;
cin>>paramNum;
l.p[i] = initRectangle(paramNum);
}
l.showAll();
cout<<l.isCollide()<<endl;
}
iscollide函数我觉得是有一定难度的,需要重点看看。