第十一章 继承与派生
1.shape类的继承
【问题描述】定义一个Shape基类,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积,使用Rectangle类创建一个派生类Square。并应用相应类的对象测试。【注意:π取3.14】
【输入形式】三种形状基本数据。
【输出形式】 对应每种形状的面积。
【样例输入】
5 4 6 5
【样例输出】
The area of the circle is 78.5
The area of the rectangle is 24
The area of the Square is 25
【样例说明】第一行的数据为基本数据(四个),分别为圆形半径,长方形长和宽,正方形边长。
#include<iostream>
using namespace std;
class Shape {
public:
Shape(){}
~Shape(){}
virtual float GetArea() {return -1;}
};
class Circle :public Shape
{
private:
int radium;
public:
Circle(int r)
{
radium=r;
}
~Circle(){}
float GetArea()
{
return 3.14*radium*radium;
}
};
class Rectangle:public Shape
{
private:
int length,hight;
public:
Rectangle(int l,int h)
{
length=l;
hight=h;
}
~Rectangle(){}
float GetArea()
{
return length*hight;
}
};
class Square: public Rectangle
{
public:
Square(int side):Rectangle(side,side){}
~Square(){}
};
int main()
{
Shape *sp;
int radium,length,hight,side;
cin>>radium>>length>>hight>>side;//radium为圆形半径,length和hight分别为长方形长和宽,side为正方形边长
sp=new Circle(radium);
cout<<"The area of the circle is "<<sp->GetArea()<<endl;
sp=new Rectangle(length,hight);
cout<<"The area of the rectangle is "<<sp->GetArea()<<endl;
sp=new Square(side);
cout<<"The area of the Square is "<<sp->GetArea()<<endl;
delete sp;
return 0;
}