如何设计一个名为Rectangle的矩形类?

2025-06-20 09:30:03
推荐回答(2个)
回答1:

  1. #include

  2. #include

  3. class point{double x;double y;public :   point(double a=0,double b=0){  x=a;y=b; }

  4. void set(double a,double b){x=a;y=b;}      

  5. double getX(){return x;}double getY(){return y;}};

  6. class Rectangle{

private:

point lpoint,rpoint;

public:

Rectangle(point l,point r)

{

lpoint=l;

rpoint=r;

}

double Area()

{

return getlength()*getwidth();

double getlength()

{

return abs(lpoint.getX()-rpoint.getX());

}

double getwidth()

{

return abs(lpoint.getY()-rpoint.getY());

}

int main()

{

point lt,rb;

double a,b;

cout<<"输入左上角坐标:  ";

cin>>a>>b;

lt.set(a,b);

cout<<"输入右下角坐标:  ";

cin>>a>>b;

rb.set(a,b);

Rectangle  rt(lt,rb);

cout<<"矩形的面积等于"<

return 0;

}

Rectangle是一个函数,使用该函数画一个矩形,可以用当前的画笔画矩形轮廓,用当前画刷进行填充。函数原型:BOOL Rectangle(HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

回答2:

Rectangle类定义如下:
class Point{ //先定义一个坐标类
int x,y;
public:
void setPoint(int m,int n){x=m;y=n;}
int getx(){return x;}
int gety(){return y;}
};
class Rectabgle{
Point p1,p2;
public:
Rectangle(int,int,int,int); //构造函数
void getPoint(Point,int&,int&);//获取坐标
void calcu(Point,Point);//计算矩形面积
~Rectangle(){cout<<"析构函数已调用!"<};
Rectangle::Rectangle(int a,int b,int c,int d){
p1.setPoint(a,b);
p2.setPoint(c,d);
}
void Rectangle::getPoint(Point p,int &a,int &b){
a=p.getx();
b=p.gety();
}
int Rectangle::calcu(Point a,Point b){
int x1,x2,y1,y2;
getPoint(x1,y1);
getPoint(x2,y2);
return (y1-y2)*(x1-x2);
}