题目:
设计一个Rectangle类,属性为矩形的左下角与右上角两个坐标,计算矩形面积。
题目分析:
可知根据题目要求需先定义一个点类用于存储两个点的坐标
class Point2
{
public:
int x;
int y;
void setPoint2(int xx, int yy)
{
this->x = xx;
this->y = yy;
}
};
然后定义一个Rectangle类
class Rectangle
{
public:
Point2 rightPoint;
Point2 leftPoint;
Rectangle(int rx, int ry, int lx, int ly)
{
rightPoint.setPoint2(rx, ry);
leftPoint.setPoint2(lx, ly);
}
int Area()
{
int length = abs(rightPoint.x - leftPoint.x);
int width = abs(rightPoint.y - leftPoint.y);
return length * width;
}
};
完整代码如下
#include <iostream>
using namespace std;
class Point2
{
public:
int x;
int y;
void setPoint2(int xx, int yy)
{
this->x = xx;
this->y = yy;
}
};
class Rectangle
{
public:
Point2 rightPoint;
Point2 leftPoint;
Rectangle(int rx, int ry, int lx, int ly)
{
rightPoint.setPoint2(rx, ry);
leftPoint.setPoint2(lx, ly);
}
int Area()
{
int length = abs(rightPoint.x - leftPoint.x);
int width = abs(rightPoint.y - leftPoint.y);
return length * width;
}
};
int main()
{
Rectangle r1(0,4,4,0);
cout << "面积为:" << r1.Area() << endl;
return 0;
}