写一个程序,定义抽象基类Shape,由它派生出3个派生类,Cirle(圆形、Rectangle(矩形)、Triangle(三角形)。用一个函数printArea 分别输出以上三者的面积,3个图形的数据在定义对象时给定、
- #include<iostream>
- using namespace std;
- /*
- 圆面积S=3.14*r*r
- 矩形面积S=长*宽
- 三角形面积S=(底*高)/2
- */
- class Shape
- {
- public:
- virtual float area()const=0;
- };
- class Circle:public Shape
- {
- public:
- Circle(double a):r(a){}
- virtual float area()const{return 3.14*r*r;}
- private:
- double r;
- };
- class Rectangle:public Shape
- {
- public:
- Rectangle(double a,double b):l(a),w(b){}
- virtual float area()const{return l*w;}
- private:
- double l;
- double w;
- };
- class Triangle:public Shape
- {
- public:
- Triangle(double a,double b):d(a),h(b){}
- virtual float area()const{return (d*h)/2;}
- private:
- double d;
- double h;
- };
- void printArea(const Shape &s1)
- {
- cout<<s1.area()<<endl;
- }
- int main()
- {
- Circle c1(6.5);
- cout<<"圆面积=";
- printArea(c1);
- Rectangle r1(3,6);
- cout<<"矩形面积=";
- printArea(r1);
- Triangle t1(4,2);
- cout<<"三角形面积=";
- printArea(t1);
- }