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

2020-04-30 16:00:38来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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

 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 }

 


原文链接:https://www.cnblogs.com/Conan-jine/p/12806847.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:C++统一初始化语法(列表初始化)

下一篇:STL之list