编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算面积的函数,计算周长的函数
帮忙解答一下,谢谢啦~~ 展开
#include<iostream>
#define PI 3.1415926;
using namespace std;
class Shape //抽象类的 定义
{
public:
virtual double GetArea() = 0; //纯虚函数
virtual double GetPerim() = 0; //纯虚函数
};
class Rectangle : public Shape //矩形类,公有继承
{
public: Rectangle(double aa, double bb) //带参数的 构造函数
{
a=aa;
b=bb;
cout<<"长"<<a<<"宽"<<b<<endl;
}
virtual 埋亏double GetArea()
{
return a * b;
}
virtual double GetPerim()
{
return 2*( a + b );
}
private:
double a;
double b;
};
class Circle : public Shape //圆类,公有继承
{
public: Circle(double rr) //带参数的 构造函数
{
r=rr;
cout<<"半径"<<r<<endl;
}
孝樱 virtual double GetArea()
{
return r * r * PI;
}
virtual double GetPerim()
{
return 2 * r * PI;
}
private:
double r;
};
void main()
{
double length, width;
cout << "输入长和宽: ";
cin >巧液丛> length >> width;
Rectangle rect(length, width);
cout << "面积是:"<< rect.GetArea() << endl<<"周长是:"<<rect.GetPerim()<<endl;
double rr;
cout << "输入半径: ";
cin >> rr;
Circle cir(rr);
cout << "面积是:"<<cir.GetArea() << endl<<"周长是:"<<cir.GetPerim()<<endl;
}
广告 您可能关注的内容 |