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

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

定義點類Point,並以點類為基類,派生出直線類Line,從基類中繼承的點的資訊表示直線的中點。請閱讀下面的程式碼,並將缺少的部分寫出來。
#include<iostream>  
#include<Cmath>  
using namespace std;  
class Point //定義座標點類  
{  
public:  
    Point():x(0),y(0) {};  
    Point(double x0, double y0):x(x0), y(y0) {};  
    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類繼承的資料成員表示直線的中點  
};  
  
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;  
}  

/*
* Copyright (c) 2015,煙臺大學計算機學院
* All right reserved.
* 作者:曹莉萍
* 檔案:Demo.cpp
* 完成時間:2015年05月25日
* 版本號: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;   //直線的兩個端點
};
//建構函式,分別用初始化直線的兩個端點及由基類資料成員(屬性)描述的中點
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 "<<endl;
    pts.PrintPoint();
    cout<<" 2nd "<<endl;
    pte.PrintPoint();
    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;
}