设计一个矩形类 Rectangle,其数据成员包括矩形的左下角和右上角的坐标,要求该
类具有调整矩形左上角和右下角两个坐标的函数,可以求矩形的面积。
分析:
定义CPoint类,用于左上点和右下点
定义CRectangle,成员有左上点和右下点
要有构造函数和析构函数
加入两个函数,一个修改矩形左上点用,一个修改右下点用
加入面积计算函数
具体代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
#include "stdafx.h" #include <iostream> #include <math.h> using namespace std; class CPoint { public: float x; float y; public: CPoint() :x(0), y(0) {} CPoint(float x_, float y_) :x(x_), y(y_) {} CPoint(CPoint& p) :x(p.x), y(p.y) { } ~CPoint(){} }; class CRectangle { private: CPoint LeftTop; CPoint RightBottom; public: CRectangle(CPoint LeftTop_, CPoint RightBottom_) :LeftTop(LeftTop_), RightBottom(RightBottom_) { } ~CRectangle(){} void AdjLeftTop(CPoint LT) { LeftTop = LT; } void AdjRightBottom(CPoint RB) { LeftTop = RB; } float GetArea() { float w = RightBottom.x - LeftTop.x; float h = RightBottom.y - LeftTop.y; return fabs(w*h); } }; int main() { CRectangle Rectangle(CPoint(6, 7), CPoint(10, 30)); cout << "矩形面积:" << Rectangle.GetArea() << endl; Rectangle.AdjLeftTop(CPoint(8, 8)); cout << "调整后矩形面积:" << Rectangle.GetArea() << endl; system("pause"); return 0; } |
运行结果: