C++ 形状类继承
題目描述
聲明一個(gè) 形狀(Shape) 抽象類,由其派生出點(diǎn)(Point)類,和直線(Line) 類,三個(gè)類均有成員函數(shù)Draw(),其中Shape類的Draw()為純虛函數(shù)。給出的主函數(shù)在輸出樣例之后。
輸入描述
輸入一個(gè)不大于100的正整數(shù)n,接下來(lái)n組數(shù)據(jù)。
每組數(shù)據(jù)先輸入字符"p"或"l"。如果輸入"p",則接下來(lái)輸入2個(gè)正整數(shù)為點(diǎn)的坐標(biāo);如果輸入"l",則接下來(lái)輸入4個(gè)正整數(shù)為直線兩個(gè)端點(diǎn)的坐標(biāo)
輸出描述
依次輸出所有點(diǎn)和直線
輸入樣例
3 p 1 2 l 5 6 7 8 p 3 4輸出樣例
Draw a point (1,2) Draw a line (5,6) to (7,8) Draw a point (3,4) 主函數(shù)如下: int main(){ Shape *p[100]; int x1,y1,x2,y2,n=0;char c;cin>>n;for(int i=0;i<n;i++){cin>>c;if(c=='p'){cin>>x1>>y1;p[i]=new Point(x1,y1);}else if(c=='l'){cin>>x1>>y1>>x2>>y2;Point p1(x1,y1),p2(x2,y2);p[i]=new Line(p1,p2);}}for(int i=0;i<n;i++){p[i]->Draw(); delete p[i];} }程序代碼
#include <iostream>using namespace std;class Shape{ // 抽象類 public: virtual void Draw() = 0; // 純虛函數(shù) };class Point:public Shape{public: Point(int a, int b):x(a), y(b){}void Draw(){cout << "Draw a point(" << x << "," << y << ")\n"; }friend ostream& operator << (ostream& o, Point& p);~Point(){}private:int x, y; };ostream& operator<<(ostream& o, Point& p){o << "(" << p.x << "," << p.y << ")";return o << endl; }class Line:public Shape{public:Line(Point& aa, Point& bb):a(aa), b(bb){}void Draw(){cout << "Draw a line" << a << "to" << b << endl;}~Line(){} private:Point a, b; };int main(){ Shape *p[100]; int x1, y1, x2, y2, n = 0;char c;cin >> n;for(int i = 0; i < n; i++){cin >> c;if(c == 'p'){cin >> x1 >> y1;p[i] = new Point(x1, y1);} else if (c == 'l'){cin >> x1 >> y1 >> x2 >> y2;Point p1(x1, y1), p2(x2, y2);p[i] = new Line(p1, p2);}}for(int i = 0;i < n; i++){p[i] -> Draw(); delete p[i];} }總結(jié)
- 上一篇: STC89C52单片机 LCD1602液
- 下一篇: C++ 平面点类