欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-15 21:31:23
1 #include 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 ......
 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 }