C++编程逻辑讲解step by step:类之间的交互

题目

设计一个点类Point,再设计一个矩形类,矩形类使用Point类的两个坐标点作为矩形的对角顶点。并可以输出4个坐标值和面积。


分析

1.点类,自然维护的是一个点的坐标,

cpp 复制代码
#include < iostream >
using namespace std;
class Point{//点类
private:
int x, y;//私有成员变量,坐标
public :
Point()//无参数的构造方法,对xy初始化
Point(int a, int b)
void setXY(int a, int b)
int getX()//得到x的方法
int getY()//得到有的函数
};

2.矩形类,有两个点就能确定了

如果希望写的完整,那么就要增加一个函数init(),维护另外两个点,因为两个对角的点坐标有一定的相关性。

cpp 复制代码
class Rectangle	//矩形类
{
private:
Point point1, point2;
public :
Rectangle();//类Point的无参构造函数已经对每个对象做初始化啦,这里不用对每个点多初始化了
Rectangle(Point one, Point two)
Rectangle(int x1, int y1, int x2, int y2)
int getArea()//计算面积的函数	
};

3.函数的实现

cpp 复制代码
Point :: Point()//无参数的构造方法,对xy初始化
 {
	x = 0;
	y = 0;
}
Point :: Point(int a, int b)
 {
	x = a;
	y = b;	
}
void Point ::setXY(int a, int b)
{
	x = a;
	y = b;
}
int Point :: getX()//得到x的方法
{
	return x;
}
int Point :: getY()//得到有的函数
 {
	return y;
}
};
Rectangle :: Rectangle(){};//类Point的无参构造函数已经对每个对象做初始化,这里不用对每个点做初始化了
Rectangle ::Rectangle(Point one, Point two)
{
	point1 = one;
	point4 = two;
	init();
}
Rectangle :: Rectangle(int x1, int y1, int x2, int y2)
 {
	point1.setXY(x1, y1);
	point4.setXY(x2, y2);
	init();
}
void Rectangle :: init()//给另外两个点做初始化的函数
 {
	point2.setXY(point4.getX(), point1.getY() );
	point3.setXY(point1.getX(), point4.getY() );
}	
void Rectangle :: printPoint()//打印四个点的函数
 {   init();
cout<<"A:("<< point1.getX() <<","<< point1.getY() <<")"<< endl;
cout<<"B:("<< point2.getX() <<","<< point2.getY() <<")"<< endl;
cout<<"C:("<< point3.getX() <<","<< point3.getY() <<")"<< endl;
cout<<"D:("<< point4.getX() <<","<< point4.getY() <<")"<< endl;
}
int Rectangle :: getArea()//计算面积的函数
{
	int height, width, area;
	height = point1.getY() - point3.getY();
	width = point1.getX() - point2.getX();
	area = height * width;
	if(area > 0)
		return area;
	else
		return -area;
}};
void main()
{
Point *p1 = new Point (-15, 56), *p2 = new Point (89, -10);//定义两个点
Rectangle *r1 = new Rectangle (*p1, *p2);//用两个点做参数,声明一个矩形对象r1
Rectangle *r2 = new Rectangle (1, 5, 5, 1);//用两队左边,声明一个矩形对象r2
cout<<"矩形r1的4个定点坐标:"<< endl;
r1->printPoint();
cout<<"矩形r1的面积:"<< r1->getArea() << endl;
cout<<"\n矩形r2的4个定点坐标:"<< endl;
r2->printPoint();
cout<<"矩形r2的面积:"<< r2->getArea() << endl;
}
相关推荐
傻啦嘿哟44 分钟前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘1 小时前
js代码09
开发语言·javascript·ecmascript
q567315231 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
??tobenewyorker1 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
rzl022 小时前
java web5(黑马)
java·开发语言·前端
时序数据说2 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
jingling5552 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
oioihoii2 小时前
C++11 forward_list 从基础到精通:原理、实践与性能优化
c++·性能优化·list
m0_687399842 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
爱上语文2 小时前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端