【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章