(矿字号)高级语言程序设计 第十一章 继承与派生

第十一章 继承与派生

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;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值