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;
}
相关推荐
nashane2 分钟前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
yolo_guo35 分钟前
redis++使用: hmset 与 hmget
c++·redis
凌波粒39 分钟前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
handler011 小时前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
拾贰_C1 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
t***5442 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子199110162 小时前
Java 基础相关
java·开发语言
汉克老师3 小时前
GESP2023年9月认证C++三级( 第一部分选择题(9-15))
c++·gesp三级·gesp3级
星越华夏3 小时前
python——三角函数用法
开发语言·python