该题目有很多种解法,这里的方法主要注意一点就是类对象被当作参数传参的时候传的当然不是本体而是拷贝后的副本,因此在一个函数中对作为参数的类进行操作时并不能作用到本体身上!
(接下来就上题目吧)
题目描述
用CPoint表示点,用两个CPoint对象表示矩形类CRect的对角线两点。分别实现CPoint类和CRect类,并在主函数用输入的坐标定义4个CPoint类对象,每2个CPoint对象再构造1个CRect对象,然后写个友元函数,判断2个矩形是否重叠。
输入
判断次数
矩形1的对角线顶点坐标x1, y1, x2, y2
矩形2的对角线顶点坐标x1, y1, x2, y2
......
输出
是否重叠
输入样例1 | 输出样例1 |
3\n 1 5 2 9\n 1 3 2 4\n 5 6 7 8\n 5 7 7 7\n 2 5 1 0\n 9 4 2 9\n | not overlapped\n overlapped\n overlapped\n |
#include<iostream>
using namespace std;
class CRect;
void judge(CRect& p1,CRect& p2);
class CPoint{
int x,y;
public:
CPoint(int a,int b):x(a),y(b){;}
friend CRect;
friend void judge(CRect& p1, CRect& p2);
};
class CRect{
CPoint a1,a2;
public:
CRect(CPoint& a1,CPoint& a2):a1(a1),a2(a2){
if(a1.x>a2.x)
swap(a1.x,a2.x);
if(a1.y<a2.y)
swap(a1.y,a2.y);
}
friend void judge(CRect& p1, CRect& p2);
};
void judge(CRect& p1,CRect& p2){
int flag=1;
// cout<<"("<<p1.a1.x<<","<<p1.a1.y<<")";
// cout<<"("<<p1.a2.x<<","<<p1.a2.y<<")";
// cout<<"("<<p2.a1.x<<","<<p2.a1.y<<")";
// cout<<"("<<p2.a2.x<<","<<p2.a2.y<<")"<<endl;
if(p1.a1.x>p2.a2.x)
flag=0;
if(p1.a2.x<p2.a1.x)
flag=0;
if(p1.a1.y<p2.a2.y)
flag=0;
if(p1.a2.y>p2.a1.y)
flag=0;
if(flag)
cout<<"overlapped"<<endl;
else
cout<<"not overlapped"<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
int a,b,c,d;
cin>>a>>b>>c>>d;
if(a>c)swap(a,c);
if(b<d)swap(b,d);
CPoint a1(a,b);
CPoint a2(c,d);
CRect p1(a1,a2);
cin>>a>>b>>c>>d;
if(a>c)swap(a,c);
if(b<d)swap(b,d);
CPoint b1(a,b);
CPoint b2(c,d);
CRect p2(b1,b2);
judge(p1,p2);
}
}
这里采用的补救方式是改变源头的输入(即把swap()函数放在初始化类之前),还有第二种办法是在judge()函数中swap(),同样也能达成影响到最终结果的效果,而且第二种办法看起来可能更符合题意(毕竟方法一使得初始点都并非题义点了),只不过第二种办法需要输入的代码可能会稍微多一点。