【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;
}
发布了38 篇原创文章 · 获赞 4 · 访问量 1653

猜你喜欢

转载自blog.csdn.net/qq_15989473/article/details/103229598