注册 登录
编程论坛 C++教室

测试一个名为Retangle的矩形类,并计算该矩形类的面积

liwenbo29 发布于 2008-11-28 16:09, 1669 次点击
设计并测试一个名为Rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积
我自己写的程序请高手指点
#include "iostream.h"
#include "math.h"
class Point
{
public:
    Point(int xx=0,int yy=0){X=xx;Y=yy;}
    Point(Point &p);
    int GetX() {return X;}
    int GetY() {return Y;}
private:
    int X,Y;
};
Point::Point(Point &p)
{
    X=p.X;
        Y=p.Y;
        
}
class Rectangle
{
public:
    Rectangle(Point xp1,Point xp2);
    double GetDis(){return dist;}
private:
    Point p1,p2;
    double dist;
};
Rectangle::Rectangle(Point xp1,Point xp2)
:p1(xp1),p2(xp2)
{
    
    double x=double(p1.GetX()-p2.GetX());
    double y=double(p1.GetX()-p2.GetY());
    dist =sqrt(x*x+y*y);
}
void main ()
{
    Point myp1(4,7),myp2(9,5);
    Rectangle myd(myp1,myp2);
    cout <<"The area is:";
    cout <<myd.GetDis()<<endl;
}
5 回复
#2
quqiuyu20052008-11-28 18:23
在下不是高手,但可以请楼主注意几个地方可以写的更规范些,请共同思考。
#include "iostream.h"
#include "math.h"
class Point
{
public:
    Point(int xx=0,int yy=0){X=xx;Y=yy;}  //初始化方式
    Point(Point &p);
    int GetX() {return X;}
    int GetY() {return Y;}
private:
    int X,Y;
};
Point::Point(Point &p)//拷贝构造函数参数类型
{
    X=p.X;
        Y=p.Y;
        
}
class Rectangle
{
public:
    Rectangle(Point xp1,Point xp2);
    double GetDis(){return dist;}
private:
    Point p1,p2;
    double dist;
};
Rectangle::Rectangle(Point xp1,Point xp2)
:p1(xp1),p2(xp2)
{
   
    double x=double(p1.GetX()-p2.GetX());
    double y=double(p1.GetX()-p2.GetY());
    dist =sqrt(x*x+y*y);
}
void main ()
{
    Point myp1(4,7),myp2(9,5);
    Rectangle myd(myp1,myp2);
    cout <<"The area is:";
    cout <<myd.GetDis()<<endl;
}
#3
pmars2008-11-29 12:23
我不知道哪错了,我拿过去就开始改,之后你看看,
#include <iostream>
#include <cmath>
using namespace std;

class Point
{
public:
    Point(int xx=0,int yy=0){X=xx;Y=yy;}
    Point(Point &p);
    int GetX() {return X;}
    int GetY() {return Y;}
private:
    int X,Y;
};

Point::Point(Point &p)
{
    X=p.X;
    Y=p.Y;
        
}

class Rectangle
{
public:
    Rectangle(Point xp1,Point xp2);
    double GetDis(){return dist;}
private:
    Point p1,p2;
    double dist;
};

Rectangle::Rectangle(Point xp1,Point xp2)
{
    p1=xp1;
    p2=xp2;
    double x=double(p1.GetX()-p2.GetX());
    double y=double(p1.GetX()-p2.GetY());
    dist =sqrt(x*x+y*y);
}

int main ()
{
    Point myp1(4,7),myp2(9,5);
    Rectangle myd(myp1,myp2);
    cout <<"The area is:";
    cout <<myd.GetDis()<<endl;
    system("pause");
    return 0;
}

建议用c++版的写法!
#4
nuciewth2008-11-29 12:27
矩形的左下角与右上角
右上角和左下角各坐标的差不就是边长了。
#5
hitcolder2008-11-29 13:58
Point::Point(Point &p)
{
    X=p.X;
        Y=p.Y;
        
}
楼主这个构造函数MS没有用到啊 ,不知道用继承来写会不会好一点啊
#6
snowstorm2008-12-06 10:33
回复 第4楼 nuciewth 的帖子
那如果矩形的长边不与x轴平行 这种方法不就不行了吗
1