1、1用组合技巧写一个矩形类 尽量用多文件结构去写,多文件去写的时候注意一般要用到条件编译,防止一个类多次编译,造成类重定义错误/point.hclass Pointpublic:Point()x=0;y=0;Point(int initX,int initY);int GetX() const;int GetY() const;private:int x,y;/point.cpp#include “point.h“Point:Point(int initX,int initY)x=initX;y=initY;int Point:GetX() const return x; int Point:G
2、etY() const return y; /rect.h#include “point.h“class Rectpublic:Rect();Rect(int l,int t,int b,int r);Rect(Point topleft,Point bottomright);Rect(Rect Rect();int GetWidth() const;int GetLength() const;int GetArea();Point GetTopLeft() const;Point GetBottomRight();private:Point topLeft,bottomRight;/左上角,
3、左下角;/rect.cpp#include “rect.h“/#include “point.h“ /class type redefinitionRect:Rect()2Rect:Rect(int l,int t,int r,int b):topLeft(l,t),bottomRight(r,b)Rect:Rect(Point topleft,Point bottomright):topLeft(topleft),bottomRight(bottomright)Rect:Rect(Rect int Rect:GetLength() constreturn topLeft.GetY()-bot
4、tomRight.GetY();int Rect:GetArea()return (topLeft.GetX()-bottomRight.GetX()*(topLeft.GetY()-bottomRight.GetY();Point Rect:GetTopLeft() constreturn topLeft;Point Rect:GetBottomRight()return bottomRight;/main.cpp#include “rect.h“/#include “point.h“#include using namespace std;void main()int x1,x2,y1,y2;coutx1y1;Point p1(x1,y1);coutx2y2;Point p2(x2,y2);Rect r1(p1,p2);cout“矩形 r1 的长“r1.GetWidth()“ 矩形的宽“r1.GetLength()endl;Rect r2;cout“矩形 r2 的长“r2.GetWidth()“ 矩形的宽“r2.GetLength()endl;1