第十一週專案一·專案二----定義點類
阿新 • • 發佈:2019-02-01
/* * 程式的版權和版本宣告部分 * Copyright (c)2013, 煙臺大學計算機學院學生 * All rightsreserved. * 檔名稱: object.cpp * 作者:趙曉晨 * 完成日期: 2013年05月10日 * 版本號: 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){}; void PrintPoint(); double x,y; }; void Point::PrintPoint(){ cout<<"Point:("<<x<<","<<y<<")"; } class Line:public Point { public: Line(Point pts,Point pte):pts(pts),pte(pte){}; double Length(); void PrintLine(); private: class Point pts,pte; }; //定義line類的成員函式 double Line::Length(){ return sqrt((pts.x-pte.x)*(pts.x-pte.x)+(pts.y-pte.y)*(pts.y-pte.y)); } void Line::PrintLine(){ cout<<"point message:"<<(pts.x+pte.x)/2<<" "<<(pts.y+pts.y)/2<<endl; } //main函式進行測試 int main(){ Point ps(-2,5),pe(7,9); Line l(ps,pe); cout<<"\n The Length of Line"; cout<<l.Length()<<endl; cout<<"\n The minddle point of Line"; l.PrintLine(); }
//定義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){}; double getX() { return x; } double getY() { return y; } void PrintPoint(); //輸出點的資訊 private: double x,y; //點的橫座標和縱座標 }; void Point::PrintPoint() { cout<<"Point:("<<x<<","<<y<<")"; //輸出點 } class Line: public Point //利用座標點類定義直線類, 其基類的資料成員表示直線的中點 { public: Line(Point pts, Point pte):pts(pts),pte(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 "; pts.PrintPoint(); cout<<"\n 2nd "; pte.PrintPoint(); cout<<"\n The Length of Line: "<<Length()<<endl; } int main() { Point ps(-2,5),pe(7,9); Line l(ps,pe); l.PrintLine();//輸出直線l的資訊 cout<<"\n The middle point of Line: "; l.PrintPoint() ;//輸出直線l中點的資訊 return 0; }
結果:
體會:用初始化表對其進行初始化。
對line進行定義。