# 抽象一个形状类

3.5 6.4
3.5 6.4

22.4
11.2

#include <iostream>
using namespace std;
//定义抽象基类Shape
class Shape
{
public:
virtual double area() const =0;            //纯虚函数
};

//定义Rectangle类
class Rectangle:public Shape
{
public:
Rectangle(double w,double h):width(w),height(h) {}              //结构函数
virtual double area() const
{
return width*height;    //定义虚函数
}
protected:
double width,height;                                           //宽与高
};

class Triangle:public Shape
{
public:
Triangle(double w,double h):width(w),height(h) {}               //结构函数
virtual double area() const
{
return 0.5*width*height;    //定义虚函数
}
protected:
double width,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;
}

#include <iostream>
using namespace std;
//定义抽象基类Shape
class Shape
{
public:
virtual double area() const =0;            //纯虚函数
};

//定义Rectangle类
class Rectangle:public Shape
{
public:
Rectangle(double w,double h):width(w),height(h) {}              //结构函数
virtual double area() const
{
return width*height;    //定义虚函数
}
protected:
double width,height;                                           //宽与高
};

class Triangle:public Shape
{
public:
Triangle(double w,double h):width(w),height(h) {}               //结构函数
virtual double area() const
{
return 0.5*width*height;    //定义虚函数
}
protected:
double width,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;

}