几何图形的继承和派生
【问题描述】已知下面Shape类的定义,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数,用于计算对象的面积。再使用Rectangle类创建一个派生类Square。
自行根据需要定义相关的成员,达到以下要求:
(1)达到以上题目所规定的类族要求。
(2)编写主函数,能够动态生成半径为5的圆对象的创建,并实现面积计算和输出。
(3)主函数中能动态生成长为4,宽为6的矩形对象创建,并实现面积计算和输出。
(4)主函数中能动态生成边为5的正方形对象创建,并实现面积计算和输出。
(5)完成上述动态对象的释放。
【输入形式】无输入。
【输出形式】分别输出指定圆、长方形和正方形的面积。
【样例输入】无输入
【样例输出】
The area of the Cirele is:78.5
The area of the Recanale is:24
The area of the Recanale is:25
【程序说明】该程序可使用虚函数相关的知识。
#include<bits/stdc++.h>
using namespace std;
#define PI 3.14
//抽象类
class Shape{
public :
virtual double GetArea()=0;//纯虚函数
};
//矩形类
class Rectangle : public Shape
{
private :
double chang,kuan;
public :
//构造函数
Rectangle(double c,double k) :chang(c),kuan(k){}
double GetArea()
{
return chang*kuan;//派生类中需要重现虚函数
}
};
//正方形类
class Square : public Rectangle
{
public :
Square(double bian) :Rectangle(bian,bian){}
};
//圆类
class Circle : public Shape
{
private :
double radius;
public :
Circle(double r) : radius(r){}
double GetArea(){
return PI*radius*radius;
}
};
int main(){
Shape *shape1=new Circle (5);//动态生成
cout<<"The area of the Cirele is:";
cout<<shape1->GetArea();
cout<<endl;
Shape *shape2=new Rectangle (4,6);
cout<<"The area of the Recanale is:";
cout<<shape2->GetArea();
cout<<endl;
Shape *shape3=new Square (5);
cout<<"The area of the Recanale is:";
cout<<shape3->GetArea();
//释放过程
if(shape1!=NULL){
delete shape1;
}
if(shape2!=NULL){
delete shape2;
}
if(shape3!=NULL){
delete shape3;
}
}