实验内容
(2) 设计一个Rectangle类,其中包括两个数据成员为Point类的对象,分别表示矩形左下角和右上角的两个顶点,要求定义相应的类求解矩形的面积。
实现过程
1、操作步骤:
图形:
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;
}