第十一週專案三點類派生直線類(有疑問)
阿新 • • 發佈:2019-01-11
/* * 程式的版權和版本宣告部分 * Copyright (c)2014, 煙臺大學計算機學院學生 * All rightsreserved. * 檔名稱:student .cpp * 作者:紀麗娜 * 完成日期:2014年5月7日 * 版本號: 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){} double getX() { return x; } double getY() { return y; } void PrintPoint(); //輸出點的資訊 protected: double x,y; //點的橫座標和縱座標 }; void Point::PrintPoint() { cout<<"Point: ("<<x<<","<<y<<")"<<endl; //輸出點 } class Line: public Point //利用座標點類定義直線類, 其基類的資料成員表示直線的中點 { public: Line(Point pts, Point pte); //建構函式,用初始化直線的兩個端點及由基類資料成員描述的中點 double Length(); //計算並返回直線的長度 void PrintLine(); //輸出直線的兩個端點和直線長度 private: Point pts,pte; //直線的兩個端點,從Point類繼承的資料成員表示直線的中點 }; //建構函式,分別用初始化直線的兩個端點及由基類資料成員(屬性)描述的中點 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 "<<endl; pts.PrintPoint(); cout<<" 2nd "<<endl; 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::Line(Point pt1, Point pt2):Point((pt1.x+pt2.x)/2,(pt1.y+pt2.y)/2)//基類的點
{
pts=pt1;
pte=pt2; //派生類的點
}
double Line::Length() //計算並返回直線的長度
{
double dx=pts.x()-pte.x;
double dy=pts.y-pte.y;
return sqrt(dx*dx+dy*dy);
}
會提示x,y是被保護的,可是定義保護的基類的派生類不是能用嗎???
private 的才不能用啊。。。。