1. 程式人生 > >第十一週專案3--點類派生直線類

第十一週專案3--點類派生直線類

/*
*Copyright (c) 2014, 煙臺大學計算機學院
*All rights reserved.
*檔名稱:test.cpp
*作者:於凱
*完成日期:2015年5月21日
*版本號:v1.0
*/
#include<iostream>
#include<Cmath>
using namespace std;
class Point //定義座標點類
{
public:
    Point():x(0),y(0) {};
    Point(double x0, double y0):x(x0), y(y0) {};
    double getX()
    {
        return x;
    }
    double getY()
    {
        return y;
    }
    void PrintPoint(); //輸出點的資訊
protected:
    double x,y;   //點的橫座標和縱座標
};
void Point::PrintPoint()
{
    cout<<"Point: ("<<x<<","<<y<<")";    //輸出點
}
class Line: public Point   //利用座標點類定義直線類, 其基類的資料成員表示直線的中點
{
public:
    Line(Point pts, Point pte); //建構函式,用初始化直線的兩個端點及由基類資料成員描述的中點
    double Length();    //計算並返回直線的長度
    void PrintLine();   //輸出直線的兩個端點和直線長度
private:
    class Point pts,pte;   //直線的兩個端點,從Point類繼承的資料成員表示直線的中點
};
Line::Line(Point pt1, Point pt2):Point((pt1.getX()+pt2.getX())/2,(pt1.getY()+pt2.getY())/2)
{
    pts=pt1;
    pte=pt2;
}
double Line::Length()
{
    double dx = pts.getX() - pte.getX();
    double dy =pts.getY() - pte.getY();
    return sqrt(dx*dx+dy*dy);
}
void Line::PrintLine()
{
    cout<<" 1st ";
    pts.PrintPoint();
    cout<<endl;
    cout<<" 2nd ";
    pte.PrintPoint();
    cout<<endl;
    cout<<" The Length of Line: "<<Length()<<endl;
}
int main()
{
    Point ps(-2,5),pe(7,9);
    Line l(ps,pe);
    cout<<"About the Line: "<<endl;
    l.PrintLine();  //輸出直線l的資訊:兩端點及長度
    cout<<"The middle point of Line is: ";
    l.PrintPoint(); //輸出直線l中點的資訊
    return 0;
}


執行結果: