实验——抽象类与虚函数


  1 class Shape
  2 {
  3 public:
  4     virtual double S()=0;
  5     virtual double C()=0;
  6 };
  7 class Circle:public Shape
  8 {
  9 public:
 10     Circle(double ir);
 11     double S();
 12     double C();
 13 private:
 14     double r;
 15 };
 16 class Square:public Shape
 17 {
 18 public:
 19     Square(double ia);
 20     double S();
 21     double C();
 22 private:
 23     double a;
 24 };
 25 class Rectangle:public Shape
 26 {
 27 public:
 28     Rectangle(double iw,double ih);
 29     double S();
 30     double C();
 31 private:
 32     double w;
 33     double h;
 34 };
 35 
 1 #include 
 2 #include "Circle.h"
 3 #include "Square.h"
 4 #include "Rectangle.h"
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     int i=0;
11     double c,s;
12     double sum=0;
13 
14     Circle circle1(1);
15     Square square1(2);
16     Rectangle rectangle1(3,4);
17 
18     Shape * p[3];
19     p[0]=&circle1;
20     p[1]=&square1;
21     p[2]=&rectangle1;
22 
23     cout<"Circle:"<<endl;
24     for(i=0;i<3;i++)
25     {
26         c=p[i]->C();
27         cout<<"c"<"="<endl;
28     }
29     cout<"Square:"<<endl;
30     for(i=0;i<3;i++)
31     {
32         s=p[i]->S();
33         cout<<"s"<"="<endl;
34         sum+=s;
35     }
36     cout<<"total area="<endl;
37     return 0;
38 }

相关