帮忙看看这道C++的题怎么写吧,谢谢啦,最好有讲解

来源:百度知道 编辑:UC知道 时间:2024/05/07 09:21:39
定义一个Shape抽象类,在此基础上派生出Rectangle和Circle类,二者均有GetArea成员函数用于计算对象的面积,GetPerim成员函数计算对象的周长;在主程序中对它们进行测试。

刚刚忘了打就提交了= =

#include <iostream>
using namespace std;

class Shape //定义一个Shape抽象类
{
public:
virtual double GetArea()=0;
virtual double GetPerim()=0;
};

class Rectangle : public Shape //派生Rectangle
{
public:
Rectangle(double h, double w) : height(h), width(w){}
double GetArea(){ return height * width; } //计算面积
double GetPerim(){ return 2*(height+width); } //计算周长
private:
double height;
double width;
};
class Circle : public Shape //派生Circle类
{
public:
Circle(double r):radius(r){}
double GetArea(){ return 3.14 * radius * radius; } //计算面积
double GetPerim(){ return 2 * 3.14 * radius; } //计算周长
private:
double radius;
};

void main()
{
Rectangle r(3,4);
cout<<"area of rectangle:"<<r.GetArea()<<endl;
cout<<"perim of rectangle:"<<r.GetPerim()<<endl;<