【C++】第11章作业


B站网课推荐


继承与派生(1)


继承与派生(2)


继承与派生(3)


继承与派生(4)


三个选择题

在这里插入图片描述

Shape类的继承

【问题描述】定义一个Shape基类,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积,使用Rectangle类创建一个派生类Square。并应用相应类的对象测试。【注意:π取3.14】

【输入形式】三种形状基本数据。

【输出形式】对应每种形状的面积。
在这里插入图片描述
【样例说明】第一行的数据为基本数据(四个),分别为圆形半径,长方形长和宽,正方形边长。

#include<iostream>
using namespace std;
class Shape { 
public: 
   Shape(){}  
  ~Shape(){} 
  virtual float GetArea() {return -1;} 
}; 
class Circle :public Shape 
{
   private:
   	float r;
   public:
   	Circle(float rr):r(rr){}
   	virtual  float  GetArea()
   	{
   		return (3.14*r*r);
   	}  
};
class Rectangle:public Shape 
{
   protected:
   	float l,h;
   public:
   	Rectangle(float ll,float hh):l(ll),h(hh){}
   	virtual  float  GetArea()
   	{
   		return (l*h);
   	}
};
class Square: public Rectangle
{
   public:
   	Square(float ss):Rectangle(ss,ss){}
   	virtual  float  GetArea()
   	{
   		return (h*l);
   	}
};
int main() 
{ 
   Shape *sp; 
   int radium,length,hight,side;
   cin>>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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值