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;
}
相关推荐
第二只羽毛2 分钟前
C++ 高并发内存池4
java·大数据·linux·c++·算法
散峰而望5 分钟前
【数据结构】并查集从入门到精通:基础实现、路径压缩、扩展域、带权,一网打尽
数据结构·c++·算法·github·剪枝·推荐算法
羚羊角uou11 分钟前
【Linux网络】select详解
linux·服务器·开发语言·网络·c++
C++ 老炮儿的技术栈11 分钟前
c++ this 指针的用途
c语言·开发语言·c++·windows·qt·github
watersink12 分钟前
第7章 软件架构设计
java·开发语言
风舞雪凌月15 分钟前
【趣谈】移动系统和桌面系统编程语言思考
java·c语言·c++·python·学习·objective-c·swift
jinanwuhuaguo16 分钟前
Claude Code 深度学习与场景应用完全指南:从入门到精通的全景实战
开发语言·人工智能·深度学习
Ricky_Theseus18 分钟前
C++全局变量、局部变量、静态全局变量、静态局部变量的区别
开发语言·c++
小此方19 分钟前
Re:从零开始的 C++ STL篇(十)map/set使用精讲:常见问题与典型用法(上)
开发语言·数据结构·c++·算法·stl
88号技师21 分钟前
2025年11月一区SCI-壁虎优化算法Gekko Japonicus Algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法