# 纯虚函数与基类指针数组的运用 代码参考

0
11
``` 1 #include <iostream>
2
3 using namespace std;
4
5 class Shape
6 {
7     public:
8         virtual double printArea()=0;
9         virtual void printName()=0;
10
11 };
12
13 class Circle:public Shape
14 {
15     private:
16         double r;
17     public:
18         Circle(double r){this->r=r;}
19         double printArea(){return 3.14159*r*r;}
20         void printName()
21         {
22             cout<<"圆:半径="<<r<<",面积:"<<printArea()<<endl;
23         }
24 };
25
26 class Square:public Shape
27 {
28     private:
29         double  a;
30     public:
31         Square(double a){this->a=a;}
32         double printArea(){return a*a; }
33         void printName()
34         {
35             cout<<"正方形:边长="<<a<<",面积:"<<printArea()<<endl;
36         }
37 };
38
39 class Rectangle:public Shape
40 {
41     private:
42         double a,b;
43     public:
44         Rectangle(double a,double b){this->a=a;this->b=b;}
45         double printArea(){return a*b;}
46         void printName()
47         {
48             cout<<"长方形:长="<<a<<",宽="<<b<<",面积:"<<printArea()<<endl;
49         }
50 };
51
52 class Trapezoid:public Shape
53 {
54     private:
55         double a,b,c;
56     public:
57         Trapezoid(double a,double b,double c){this->a=a;this->b=b;this->c=c;}
58         double printArea(){return (a+b)*c*0.5;}
59         void printName()
60         {
61             cout<<"梯形:上底="<<a<<",下底="<<b<<",高="<<c<<",面积:"<<printArea()<<endl;
62         }
63 };
64
65 class Triangle:public Shape
66 {
67     private:
68         double a,b;
69     public:
70
71         Triangle(double a,double b){this->a=a;this->b=b;}
72         double printArea(){return a*b*0.5;}
73         void printName()
74         {
75             cout<<"三角形:底边="<<a<<",高="<<b<<",面积:"<<printArea()<<endl;
76         }
77 };
78
79 int main()
80 {
81     double r,x,a,b,m,n,l,s,h;
82     double area=0.0;
83     cin>>r>>x>>a>>b>>m>>n>>l>>s>>h;
84     Shape *p[5];
85     p[0]=new Circle(r);
86     p[1]=new Square(x);
87     p[2]=new Rectangle(a,b);
88     p[3]=new Trapezoid(m,n,l);
89     p[4]=new Triangle(s,h);
90     for(int i=0;i<5;i++)
91     {
92         p[i]->printName();
93         area+=p[i]->printArea();
94     }
95     cout<<"总面积:"<<area<<endl;
96     return 0;
97 }```

<