继承

编写C++程序完成以下功能:
(1) 声明一个基类Shape(形状),其中包含一个方法来计算面积;
(2) 从Shape派生两个类矩形和圆形;
(3) 从矩形派生正方形;
(4) 分别实现派生类构造函数、析构函数和其他方法;
(5) 创建派生类的对象,观察构造函数、析构函数调用次序;
(6) 不同对象计算面积。

#include<iostream>
#define PI 3.1415
using namespace std;
class Shape
{ 
public:
                   Shape() {cout<<"调用构造函数Shape"<<endl;}
                   ~Shape() {cout<<"调用析构函数Shape"<<endl;}
                   double Girth() {}
                   double Area() {}
};
class Rectangle: public Shape
{
private:
                   double len;
                   double wide;
public:
                   Rectangle(double l=0,double w=0) {len=l; wide=w; cout<<"调用构造函数Rectangle"<<endl;}
                   void SetRectangle(double l=0,double w=0) {len=l; wide=w;}
                   ~Rectangle(){cout<<"调用析构函数Rectangle"<<endl;}
                   double Girth() {return (len+wide)*2;}
                   double Area() {return len*wide;}
};
class Circle:public Shape
{
private: 
                   double r;
public:
                   Circle(double radius=0) {r=radius; cout<<"调用构造函数Circle"<<endl;}
    void SetCircle(double radius=0) {r=radius;}
                   ~Circle(){cout<<"调用析构函数Circle"<<endl;}
                   double Girth() {return 2*PI*r;}
                   double Area() {return PI*r*r;}
};
class Square:public Rectangle
{
public:
                   Square(double x=0) {Rectangle(x,x); cout<<"调用构造函数Square"<<endl;}
    void SetSquare(double x=0) {SetRectangle(x,x);}
                   ~Square(){cout<<"调用析构函数Square"<<endl;}
};
int main()
{
                   Rectangle b;
                   Circle c;
                   Square d;
                   double x,y,m,n;
                   cout<<endl<<"请输入矩形长和宽(用空格隔开):"<<endl;
                   cin>>x>>y;
                   b.SetRectangle(x,y);
                   cout<<"矩形周长为:"<<b.Girth()<<endl;
                   cout<<"矩形面积为:"<<b.Area()<<endl;
    cout<<endl<<"请输入圆形的半径:"<<endl;
                   cin>>m;
                   c.SetCircle(m);
                   cout<<"圆形周长为:"<<c.Girth()<<endl;
                   cout<<"圆形面积为:"<<c.Area()<<endl;
    cout<<endl<<"请输入正方形的边长:"<<endl;
                   cin>>n;
                   d.SetSquare(n);
                   cout<<"正方形周长为:"<<d.Girth()<<endl;
                   cout<<"圆形面积为:"<<d.Area()<<endl;
                   system("pause");
                   cout<<endl;
                   return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值