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;
}
相关推荐
雨田言炎1 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody2 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
ZhangShao06072 小时前
题解:CF2249B
c++·算法
用户昵称1003 小时前
C/C++编程-工程实践-本地存储log的工程意义
c语言·开发语言
吹什么轩4 小时前
c++复习:map和set的使用
开发语言·c++
必须得开心呀4 小时前
qt生成dump文件并定位异常
开发语言·qt
fpcc4 小时前
跟我学C++中级篇—内存流
开发语言·c++
Cicada1284 小时前
ccvt:一个用 Rust 写的中国地图坐标系互转命令行工具
开发语言·后端·rust