判断矩形是否重叠(复合类+友元)

判断矩形是否重叠(复合类+友元)
题目描述

用CPoint表示点,用两个CPoint对象表示矩形类CRect的对角线两点。分别实现CPoint类和CRect类,并在主函数用输入的坐标定义4个CPoint类对象,每2个CPoint对象再构造1个CRect对象,然后写个友元函数,判断2个矩形是否重叠。

输入

判断次数

矩形1的对角线顶点坐标x1, y1, x2, y2

矩形2的对角线顶点坐标x1, y1, x2, y2

输出

是否重叠

示例输入

3
1 5 2 9
1 3 2 4
5 6 7 8
5 7 7 7
2 5 1 0
9 4 2 9

样例输出

not overlapped
overlapped
overlapped

#include <iostream>
using namespace std;
#include <iomanip> 


class CPoint{
	public:
		CPoint(){
		}
	CPoint(int a,int b){
		x1=a;
		y1=b;
	}	
	void set(int a,int b){
		x1=a;
		y1=b;
	}
//	private:
		int x1;
		int y1;

	}; 
	
class CRect{
	public:
	CRect(){
	}
	CRect(int a,int b,int c,int d):cp1(a,b),cp2(c,d){
	}
	friend bool isnot(CRect &cr1,CRect &cr2);
	private:
	CPoint cp1;
	CPoint cp2;
	
	
	
};
 bool isnot(CRect &cr1,CRect &cr2){//算法相关 
 	
	return cr1.cp2.x1<=cr2.cp1.x1||cr1.cp2.y1<=cr2.cp1.y1||cr1.cp1.x1>=cr2.cp2.x1||cr1.cp1.y1 >=cr2.cp2.y1;
}

int main(){

	int t;
	cin>>t;
	int x1,y1,x2,y2,x3,y3,x4,y4;
	 
	while(t--){
		cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
		CPoint cp1,cp2,cp3,cp4;
		
		cp1.set(x1,y1);
		cp2.set(x2,y2);
		cp3.set(x3,y3);
		cp4.set(x4,y4);
		CRect cr1(x1,y1,x2,y2);
		CRect cr2(x3,y3,x4,y4);
		if(isnot(cr1,cr2) )cout<<"not overlapped"<<endl;
		else cout<<"overlapped"<<endl; 
		
		
		
		
		
	
	} 

	return 0;
}

问题1:怎么写构造函数复合类的构造函数?(不同于继承)

public:
CRect(int a,int b,int c,int d):cp1(a,b),cp2(c,d){
	}
private:
	CPoint cp1;
	CPoint cp2;

之后会写一遍讨论继承和复合的区别

猜你喜欢

转载自blog.csdn.net/weixin_49977305/article/details/121185721
今日推荐