【sy3_类组合的应用与编程_2_Rectangle】

实验内容

(2) 设计一个Rectangle类,其中包括两个数据成员为Point类的对象,分别表示矩形左下角和右上角的两个顶点,要求定义相应的类求解矩形的面积。

实现过程
1、操作步骤:

图形:

image-20220916203538331

2、整段代码:

Point.h

#pragma once
#include<iostream>
using namespace std;
#ifndef POINT_H
#define POINT_H
class Point
{
private:
	float x, y;
public:
	Point();
	Point(int xx, int yy);
	Point(Point& p);
	float getX();
	float getY();
};
#endif 

Rectangle.h

#pragma once
#include<iostream>
#include <math.h> 
#include "Point.h"
using namespace std;
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
private:
	Point p1;
	Point p2;
public:
	Rectangle();
	Rectangle(Point xp1, Point xp2);
	Rectangle(Rectangle& rec);
	float computeArea();
};
#endif 

Point.cpp

#include "Point.h"
Point::Point()
{
	x = 0;
	y = 0;
}
Point::Point(int xx, int yy)
{
	x = xx;
	y = yy;
}
Point::Point(Point& p)
{
	x = p.x;
	y = p.y;
}
float Point::getX()
{
	return x;
}
float Point::getY()
{
	return y;
}

Rectangle.cpp

#include "Rectangle.h"
Rectangle::Rectangle()
{
}
Rectangle::Rectangle(Point xp1, Point xp2) :p1(xp1), p2(xp2)
{
}
float Rectangle::computeArea()
{
	float length = fabs(p2.getX() - p1.getX());
	float width = fabs(p2.getY() - p1.getY());
	return length * width;
}

main.cpp

#include <iostream>
#include "Rectangle.h"
using namespace std;
int main() {
	Point p3;
	Point p4(10, 20);
	Rectangle r1(p3, p4);
	cout << "矩形r1的面积为:" << r1.computeArea() << endl;
	return 0;
}
3、运行结果:

image-20220919150622317

4、分析

【问答】2022年9月16日C++课后作业——类组合

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值