第十週任務一 線類繼承點類

/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生 
* All rights reserved.
* 文件名稱:  point to line                            
* 作    者:   姜雅明                              
* 完成日期:   2012      年   04    月    24    日
* 版 本 號:          

* 對任務及求解方法的描述部分
* 輸入描述: 兩個點的座標
* 問題描述: 根據兩個點,計算直線的中點和長度
* 程序輸出: 直線的中點和長度
* 程序頭部的註釋結束
*/

#include<iostream>
#include<Cmath>

using namespace std;

class Point //定義座標點類
{
public:
	double x, y;   //點的橫座標和縱座標
	Point(){x = 0;y = 0;}
	Point(double x0,double y0) {x = x0; y = y0;} 
	void PrintP(){cout << "Point:(" << x << "," << y << ")" << endl;}
};  
class Line: public Point   //利用座標點類定義直線類, 其基類的數據成員表示直線的中點
{
private:
	class Point pt1,pt2;   //直線的兩個端點
public:
	Line(Point pts, Point pte);  //構造函數
	double Dx(){return pt2.x-pt1.x;}
	double Dy(){return pt2.y-pt1.y;}
	double Length();//計算直線的長度
	void PrintL();  //輸出直線的兩個端點和直線長度
};

//構造函數,分別用參數初始化對應的端點及由基類屬性描述的中點
Line::Line(Point pts, Point pte):Point ((pte.x + pts.x) / 2, (pte.y + pts.y) / 2), pt1(pte), pt2(pts){};

double Line::Length(){return sqrt(Dx() * Dx() + Dy() * Dy());};//計算直線的長度

void Line::PrintL()
{
	cout << " 1st ";

	pt1.PrintP();

	cout << " 2nd ";

	pt2.PrintP();

	cout << " The middle point of Line: ";

	PrintP();

	cout << " The Length of Line: " << Length() << endl;
}
int main()
{
	Point ps(-2,5),pe(7,9);

	Line l(ps,pe);

	l.PrintL();//輸出直線l的信息

	pe.PrintP();  
	ps.PrintP();//輸出直線l中點的信息

	system("pause");
	return 0;
}


輸出結果:

/* 1st Point:(7,9)
* 2nd Point:(-2,5)
* The middle point of Line: Point:(2.5,7)
* The Length of Line: 9.84886
*Point:(7,9)
*Point:(-2,5)
*請按任意鍵繼續. . .
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章