01./* (程序頭部註釋開始)
02.* 程序的版權和版本聲明部分
03.* Copyright (c) 2011, 煙臺大學計算機學院學生
04.* All rights reserved.
05.* 文件名稱:
06.* 作 者: 王明星
07.* 完成日期: 2012 年 4 月 16 日
08.* 版 本 號:
09.
10.* 對任務及求解方法的描述部分
11.* 輸入描述:
12.* 問題描述:實現分數類中的<<和>>運算符重載,實現分數的輸入和輸出
13.* 程序頭部的註釋結束
14.*/
#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();//輸出直線的兩個端點和直線的長度
};
//構造函數,分別用參數初始化對應的端點及基類屬性描述的中點
Line::Line(Point pts,Point pte):Point((pte.x+pts.x)/2,(pte.y+pts.y)/2),pt1(pts),pt2(pte){}
double Line::Length(){return sqrt(Dx()*Dx()+Dy()*Dy());}//計算直線的長度
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;
}
int main()
{
Point ps(-2,5),pe(7,9);
Line L(ps,pe);
L.printL();//輸出直線l的信息
L.printp();//輸出直線l中點的信息
system("pause");
return 0;
}
上機感言:派生類也是一個類,不過是在基類的基礎上擴充得到的類罷了!