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

第十一週 專案三:點類派生直線類

問題及程式碼:

/*
* Copyright (c) 2015, 煙臺大學計算機學院
* All rights reserved.
* 檔名稱:Project4.cpp
* 作    者:李楠
* 完成日期:2015年5月17日
* 版 本 號:v1.0
*
* 問題描述:定義點類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(); //輸出點的資訊
    double displayx();
    double displayy();
protected:
    double x,y;   //點的橫座標和縱座標
};
void Point::PrintPoint()
{
    cout<<"Point: ("<<x<<","<<y<<")"<<endl;    //輸出點
}
double Point::displayx()
{
    return x;
}
double Point::displayy()
{
    return y;
}
class Line: public Point   //利用座標點類定義直線類, 其基類的資料成員表示直線的中點
{
public:
    Line(Point pts, Point pte); //建構函式,用初始化直線的兩個端點及由基類資料成員描述的中點
    double Length();    //計算並返回直線的長度
    void PrintLine();   //輸出直線的兩個端點和直線長度
private:
    class Point pts,pte;   //直線的兩個端點,從Point類繼承的資料成員表示直線的中點
};
Line::Line(Point pts1, Point pte1):Point((pts1.displayx()+pte1.displayx())/2,(pts1.displayy()+pte1.displayy())/2)
{
    pts=pts1;
    pte=pte1;
}
double Line::Length()
{
    double x;
    double y;
    x = pts.displayx() - pte.displayx();
    y = pts.displayy() - pte.displayy();
    return sqrt(x*x+y*y);
}
void Line::PrintLine()
{
    cout<<" 1st ";
    pts.PrintPoint();
    cout<<" 2nd ";
    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;
}

執行結果:

知識點總結:
注意Line類的建構函式的定義,然後我又根據輸出樣例修改了一下原來程式的小錯誤


學習心得:
還有專案四一個大專案,讓我明天下午再掙扎吧,晚安了