C++知识:定义一个抽象类shape应以计算面积,

2024-10-29 11:55:15
推荐回答(1个)
回答1:

#include
using namespace std;

class Shape //抽象基类
{
protected:
double s;
public:
Shape(){s=0;} //构造函数
virtual double Area() = 0; //面积计算函数(纯虚函数)
};

class Rect:public Shape //派生类——矩形
{
private:
double width;
double height;
public:
Rect(double w,double h) //构造函数
{
width=w; //宽
height=h; //高
}
double Area() //面积计算函数(实现)
{
s=width*height;
return s;
}
};

class Circle:public Shape //派生类——圆形
{
private:
double radius; //半径
public:
Circle(double r){radius=r;} //构造函数
double Area() //面积计算函数(实现)
{
s=3.14159*radius*radius;
return s;
}
};

class Trapezium:public Shape //派生类——梯形
{
private:
double top; //上底
double bottom; //下底
double height; //高
public:
Trapezium(double t,double b,double h) //构造函数
{
top=t;
bottom=b;
height=h;
}
double Area() //面积计算函数(实现)
{
s=(top+bottom)*height/2;
return s;
}
};

void main()
{
Shape *pShape; //声明抽象基类指针
Rect rect(3,5);
Circle circle(4);
Trapezium trapezium(3.5,5.5,7);
pShape = ▭ //抽象基类指针指向矩形
cout<<"矩形面积:"<Area()< pShape = &circle; //抽象基类指针指向圆形
cout<<"圆形面积:"<Area()< pShape = &trapezium; //抽象基类指针指向梯形
cout<<"梯形面积:"<Area()<}