第十七週自由練習項目——acm抽象ベースクラス

2097 ワード

/* 
*            : 
*Copyright(c)2014,            
*All rights reserved. 
*    :acm     
*  :    
*    :2014   6   16   
*   :v1.0 
*             : 
*    : 
*    :       ,      Shape,     3    : Circle(  )、Rectangle(  )、Triangle(   ),
                printArea           (        ),3              。
*    :   
*    :    ,       
*    : 
*    : 
*/
#include <iostream>
#include <iomanip>
using namespace std;
const float m=3.1415926;
class Shape
{
public:
    virtual float printArea() =0;
};
class Circle:public Shape
{
public:
    Circle(float r):R(r) {}
    virtual float printArea()
    {
        return (m*R*R);
    }
protected:
    float R;
};
class Rectangle:public Shape
{
public:
    Rectangle(float l1,float l2):length1(l1),length2(l2) {}
    virtual float printArea()
    {
        return (length1*length2);
    }
protected:
    float length1,length2;
};
class Triangle:public Shape
{
public:
    Triangle(float h,float w):hight(h),width(w) {}
    virtual float printArea()
    {
        return hight*width/2;
    }
protected:
    float hight,width;
};
void printArea(Shape &shape)
{
    cout<<shape.printArea()<<endl;
}
int main()
{
    float r,a,b,w,h;
    cout<<fixed<<setprecision(2);
    cin>>r;
    Circle circle(r);
    cout<<"area of circle = ";
    printArea(circle);
    cin>>a>>b;
    Rectangle rectangle(a,b);
    cout<<"area of rectangle = ";
    printArea(rectangle);
    cin>>w>>h;
    Triangle triangle(w,h);
    cout<<"area of triangle = ";
    printArea(triangle);
    return 0;
}

*サンプル出力:
*心得:重傷を負っても体は軽い.