c++继承的简单问题,circle,rectangle继承shape

#define PI 3.14
#include<iostream>
using namespace std;

/*建立一个形状类Shape作为基类,派生出圆类Circle和矩形类Rectangle,求出面积并获取相关信息。具体要求如下:
(1)形状类Shape
(a)保护数据成员
double x,y:对于不同的形状,x和y表示不同的含义,如对于圆,x和y均表示圆的半径,而对于矩形,x表示矩形的长,y表示矩形的宽。访问权限定义为保护类型是为了能被继承下去,以便派生类能直接访问x和y。
(b)公有成员函数
构造函数Shape(double _x,double _y):用_x、_y分别初始化x、y。
double GetArea():求面积,在此返回0.0。*/

class Shape
{
protected:
    double x,y;
public:
    Shape(double _x,double _y);
    double GetArea();
};

double Shape::GetArea()
{
    return 0;
}
Shape::Shape(double _x,double _y)
{
    x=_x;
    y=_y;
}

/*圆类Circle,从Shape公有派生
(a)公有成员函数
Circle(double r):构造函数,并用r构造基类的x和y。
double GetArea():求圆的面积。
double GetRadius():获取圆的半径。*/

class Circle:public Shape
{
public:
    Circle(double r);
    double GetArea();
    double GetRadius();
};
Circle::Circle(double r):Shape(0.0,0.0)     //此处构造函数要用上初始化列表,构造Shape
{
    x=r;
    y=r;
}
double Circle::GetArea()
{
    return PI*x*y;
}
double Circle::GetRadius()
{
    return x;
}

/*矩形类Rectangle,从Shape公有派生
(a)公有成员函数
Rectangle(double l,double w) :构造函数,并用l和w构造基类的x和y。
double GetArea():求矩形的面积。
double GetLength():获取矩形的长。
double GetWidth():获取矩形的宽。*/

class Rectangle:public Shape
{
public:
    Rectangle(double l,double w);
    double GetArea();
    double GetLength();
    double GetWidth();
};
Rectangle::Rectangle(double l,double w):Shape(0.0,0.0)        //此处构造函数要用上初始化列表,构造Shape
{
    x=l;
    y=w;
}
double Rectangle::GetArea()
{
    return x*y;
}
double Rectangle::GetLength()
{
    return x;
}
double Rectangle::GetWidth()
{
    return y;
}

/*在主函数中对派生类进行测试。注意,在程序的开头定义符号常量PI的值为3.14。测试的输出结果如下:
circle:r=1, area=3.14
rectangle:length=3, width=4, area=12*/
int main()
{
    Circle c(1);
    Rectangle r(3,4);
    
    cout<<"circle:"<<" "<<"r="<<c.GetRadius()<<" "<<"area="<<c.GetArea()<<endl;
    cout<<"rectangle:"<<" "<<"length="<<r.GetLength()<<" "<<"width="<<r.GetWidth()<<" "<<"area="<<r.GetArea()<<endl;
    return 0;
}

//关于这个问题,刚开始学的时候碰到还是很懵逼的,现在再做真的感觉贼简单,看来自己有进步了

//优秀

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值