* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 第九周 任務一
* 作 者: 楊森
* 完成日期: 2012 年 4 月 23 日
* 版 本 號: V1.0
源程序:
#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<<")";}
};
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(); //輸出直線的兩個端點和直線長度
};
//(1)構造函數,分別用參數初始化對應的端點及由基類屬性描述的中點
Line::Line(Point pts, Point pte):Point((pts.x+pte.x)/2,(pts.y+pte.y)/2) {pt1=pts;pt2=pte;} //解題指導:此處關鍵在於其基類初始化時給對參數
double Line::Length(){return sqrt(Dx()*Dx()+Dy()*Dy());};//(2)計算直線的長度
void Line::PrintL()
{
cout<<" 1st ";
pt1.PrintP();
cout<<"\n 2nd ";
pt2.PrintP();
cout<<"\n The middle point of Line: ";
PrintP();
cout<<"\n The Length of Line: "<<Length()<<endl; //(3)輸出直線長度
}
int main()
{
Point ps(-2,5),pe(7,9);
Line l(ps,pe);
l.PrintL(); //(4)輸出直線l的信息
l.PrintP();//(5)輸出直線l中點的信息,此處再次體會:派生類的對象調用其基類提供的成員函數
system("pause");
return 0;
}
運行結果: