[YTU]_2390( 抽象一个形状类)

题目描述

阮宝同学期待着暑假来临,知道C++不好好复习麻烦不小。没有多态性,那就不叫面向对象,老师不划重点也能猜到。嘿嘿,自己做个经典题,怎么变题也不怕。老湿,再难的题还有木有?

输入

输入四个数,前两个是矩形的长和宽,后两个是三角形的底边长和高。

输出

分两行输出两个数,第一个是矩形的面积,第二个是三角形的面积。

样例输入

3.5 6.4
3.5 6.4

样例输出

22.4
11.2
#include <iostream>
using namespace std;
class Shape
{
public:
    virtual double area()const=0;
};
class Rectangle:public Shape
{
public:
    Rectangle(double h,double w):height(h),weight(w){}
virtual double area()const{return height*weight;}
private:
    double height, weight;
};
class Triangle:public Shape
{
public:
    Triangle(double w,double h):weight(w),height(h){}
    virtual double area()const{return 0.5*weight*height;}
private:
    double weight;
    double height;
};
int main()
{
    double a,b;
    cin>>a>>b;
    Rectangle r(a,b);
    Shape *s1=&r;
    cout<<s1->area()<<endl;
    double w,h;
    cin>>w>>h;
    Triangle t(w,h);
    Shape &s2=t;
    cout<<s2.area()<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/sxy201658506207/p/7586320.html