1. 程式人生 > >14-2-形狀類族的中的純虛擬函式(OJ版)

14-2-形狀類族的中的純虛擬函式(OJ版)

/*
* 作    者: 霍雨佳
* 完成日期:2014 年5月27日
* 版 本 號:v1.0
* 問題描述:形狀類族的中的純虛擬函式
* 樣例輸入:
* 樣例輸出:
* 專案要求:
*/
#include <iostream>
#include <iomanip>
#define pi 3.1415926
using namespace std;
class Shape
{
    public:
    virtual double area()=0;
};
class Circle:public Shape//(圓形)
{
    public:
    Circle(double a):r(a){}
    double area()
    {
        return pi*r*r;
    }
    private:
    double r;
};
class Square:public Shape//(正方形)、
{
    public:
    Square(double a):j(a){}
    double area()
    {
        return j*j;
    }
     private:
    double j;
};
class Rectangle:public Shape//(矩形)
{
     public:
    Rectangle(double a,double b):l(a),m(b){}
    double area()
    {
        return l*m;
    }
     private:
    double l;
    double m;
};
class Triangle:public Shape//(三角形)
{
     public:
     Triangle(double a,double b):y(a),n(b){}
    double area()
    {
        return (y*n)/2;
    }
    private:
    double y;
    double n;
};
class Trapezoid:public Shape//(梯形)、
{
    public:
     Trapezoid(double q,double s,double x):y(q),n(s),m(x){}
    double area()
    {
        return ((y+n)*m)/2;
    }
    private:
    double y;
    double n;
     double m;
};
int main()


{


    float r,a,b,w1,w2,w,h;


    cout<<fixed<<setprecision(2);


    cin>>r;


    Circle circle(r);


    cin>>a;


    Square square(a);


    cin>>a>>b;


    Rectangle rectangle(a,b);


    cin>>w1>>w2>>h;


    Trapezoid trapezoid(w1,w1,h);


    cin>>w>>h;


    Triangle triangle(w,h);


    Shape *pt[5]= {&circle,&square,&rectangle,&trapezoid,&triangle};


    double areas=0.0;


    for(int i=0; i<5; i++)


        areas=areas+pt[i]->area();


    cout<<"total of all areas="<<areas<<endl;


    return 0;


}


執行結果: