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;
}
相关推荐
集成显卡7 小时前
Rust实战七 |基于带 colored 颜色文字控制台的批量文件删除工具
开发语言·后端·rust
比昨天多敲两行7 小时前
linux 线程概念与控制
java·开发语言·jvm
huaweichenai8 小时前
php 根据每个类型的抽签范围实现抽签功能
开发语言·php
codeejun9 小时前
每日一Go-73、云原生成本优化 —— 资源限制 & 指标驱动扩容
开发语言·云原生·golang
就叫_这个吧9 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解
Sam_Deep_Thinking10 小时前
聊聊Java中的of
java·开发语言·架构
feng_you_ying_li12 小时前
C++复习二,继承与多态
c++
小小de风呀13 小时前
de风——【从零开始学C++】(十一):list的基本使用和模拟实现
开发语言·c++·list
三行数学13 小时前
Matlab之父克利夫·莫勒尔逝世
开发语言·matlab
陌路2013 小时前
C++高级进阶--夯实进阶基础(1)
开发语言·c++