Problem C: 抽象一个形状类
Description
阮宝同学期待着暑假来临,知道C++不好好复习麻烦不小。没有多态性,那就不叫面向对象,老师不划重点也能猜到。嘿嘿,自己做个经典题,怎么变题也不怕。老湿,再难的题还有木有?
Input
输入四个数,前两个是矩形的长和宽,后两个是三角形的底边长和高。
Output
分两行输出两个数,第一个是矩形的面积,第二个是三角形的面积。
Sample Input
3.5 6.4 3.5 6.4
Sample Output
22.4 11.2
HINT
#include <iostream>
#include <iomanip>
using namespace std;
class Shape
{
public:
virtual double area() const=0;
};
class Rectangle:public Shape
{
public:
Rectangle(double r,double l):weigth(r),height(l){}
virtual double area() const{return weigth*height;}
protected:
double weigth;
double height;
};
class Triangle:public Shape
{
public:
Triangle(double r,double l):weigth(r),height(l){}
virtual double area() const{return 0.5*weigth*height;}
protected:
double weigth;
double height;
};
int main()
{
double a,b;
cin>>a>>b; //输入矩形的长和宽
Rectangle r(a,b);//建立Rectangle类对象r, 矩形长a宽b
Shape *s1=&r;
cout<<s1->area()<<endl;//输出矩形的面积
double w,h;
cin>>w>>h; //输入矩形的长和宽
Triangle t(w,h); //建立Triangle类对象t,三角形底边长w高h
Shape &s2=t;
cout<<s2.area();//输出三角形面积
return 0;
}