多态性与虚函数培训教案.pptVIP

  • 1
  • 0
  • 约1.55万字
  • 约 66页
  • 2017-02-08 发布于江苏
  • 举报
多态性与虚函数培训教案

例4.6 (续一)。 #include iostream #include string using namespace std; class CPoint{ private: int X, Y; public: CPoint(int x=0, int y=0){X=x; Y=y;} CPoint(CPoint p){ X=p.X; Y=p.Y; } int GetX(){ return X; } int GetY() {return Y;} }; 例4.6 (续二)。 class CShape{ private: string Color; public: CShape(string c){Color = c;} virtual void Draw(){ cout Draw a shape. The color is Color endl; } void PrintColor(){ cout Color endl;} }; 例4.6 (续三)。 class CLine:public CShape{ private: CPoint Start; //线段的起点 CPoint End; //线段的终点 public: CLine(CPoint s, CPoint e, string c):CShape(c),Start(s),End(e){} virtual void Draw(){ cout Draw a Line from ( Start.GetX() , Start.GetY(); cout) to (End.GetX(),End.GetY() ), with color ; PrintColor(); } }; 例4.6 (续四)。 class CCircle:public CShape{ private: CPoint Center; int Radius; public: CCircle(CPoint ctr, int r, string c):CShape(c),Center(ctr){ Radius = r; } virtual void Draw(){ cout Draw a circle at center ( Center.GetX() , ; cout Center.GetY() ) with radius Radius and color ; PrintColor(); } }; 例4.6 (续五)。 int main(){ CShape *ps[3]; CShape s(Red); CPoint p1(10,10), p2(100,100),p3(50,50); CLine l(p1,p2,Green); CCircle c(p3, 20, Black); ps[0] = s; ps[1] = l; ps[2] = c; for(int i=0; i3; i++) ps[i]-Draw(); return 0; } 例4.9 (续一)。 #include iostream #include string using namespace std; class CPoint{ private: int X, Y; public: CPoint(int x=0, int y=0){X=x; Y=y;} CPoint(CPoint p){ X=p.X; Y=p.Y; } int GetX(){ return X; } int GetY() {return Y;} }; 例4.9 (续二)。 class CShape{ private: string Color; public: CShape(string c){Color = c;} virtual void Draw() = 0; void PrintColor(){ cout Color endl;} }; 例4.6 (续三)。 class CLine:public CShape{ private: CPoint Start; //线段的起点 CPoint End; //线段的终点 public: CLine(CPoint s, CPoint e, string c):CShape(c),Start(s),End(e){} virtual void Draw(){ co

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档