码迷,mamicode.com
首页 > 其他好文 > 详细

虚函数-计算图形面积

时间:2014-06-10 15:07:53      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:虚函数   多态性   

Problem B: C++习题 虚函数-计算图形面积


Description

编写一个程序,定义抽象基类Shape,由它派生出5个派生类: Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。
用虚函数分别计算几种图形面积,并求它们之和。
要求用基类指针数组,使它每一个元素指向一个派生类对象。 

Input

圆的半径
正方形的边长
矩形的边长
梯形的上底和下底,高
三角形的底与高

Output

所有图形面积之和(结果保留两位小数)

Sample Input

12.6
3.5
4.5 8.4
2.0 4.5 3.2
4.5 8.4

Sample Output

total of all areas=574.11

HINT




#include <iostream> 
#include <iomanip> 
using namespace std; 
class Shape 
{ 
public: 
    virtual double area() const=0; 
}; 
  

class Circle:public Shape 
{ 
public: 
Circle(double r):radius(r){} 
virtual double area() const{return 3.14159*radius*radius;} 
protected: 
    double radius; 
}; 


class Rectangle:public Shape 
{ 
public: 
Rectangle(double r,double l):width(r),height(l){} 
virtual double area() const{return width*height;} 
protected: 
    double width; 
    double height; 
}; 


class Triangle:public Shape 
{ 
public: 
Triangle(double r,double l):width(r),heigth(l){} 
virtual double area() const{return 0.5*width*heigth;} 
protected: 
    double width; 
    double heigth; 
}; 


class Trapezoid:public Shape 
{ 
public: 
Trapezoid(double r,double l,double k):top(r),bottom(l),height(k){} 
virtual double area() const{return 0.5*(top+bottom)*height;} 
protected: 
    double top; 
    double bottom; 
    double height; 
}; 


class Square:public Shape 
{ 
public: 
Square(double r):side(r){} 
virtual double area() const{return side*side;} 
protected: 
    double side; 
}; 

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; 
} 


虚函数-计算图形面积,布布扣,bubuko.com

虚函数-计算图形面积

标签:虚函数   多态性   

原文地址:http://blog.csdn.net/u013629228/article/details/29561505

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!