C++day5

实现一个图形类(Shape),包含受保护成员属性: 周长、面积
公共成员函数:特殊成员函数书写定义一个圆形类(Circle),继承自图形类,包含私有属性: 半径
公共成员函数: 特殊成员函数、以及获取周长、获取面积函数定义一个矩形类(Rect),继承自图形类,包含私有属性: 长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。

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

class Shape
{
protected:
    double circumference;
    double area;

public:
    Shape(){cout<<"无参构造"<<endl;}

    Shape(double cir,double area):circumference(cir),area(area)
    {
        cout<<"有参构造"<<endl;
    }

    ~Shape()
    {
        cout<<"析构函数"<<endl;
    }

    Shape(const Shape &other):circumference(other.circumference),area(other.area)
    {
        cout<<"拷贝构造函数"<<endl;
    }

    void show()
    {
        cout<<"周长="<<circumference<<endl;
        cout<<"面积="<<area<<endl;
    }
};

class Circle:public Shape
{
private:
    double radius;

public:
    Circle(){cout<<"无参构造"<<endl;}

    Circle(double radius):radius(radius)
    {
        cout<<"有参构造"<<endl;
    }
    ~Circle()
    {
        cout<<"析构函数"<<endl;
    }
    double get_cir(Circle &c)
    {
        c.circumference=2*radius*PI;
        return c.circumference;
    }

    double get_area(Circle &c)
    {
        c.area=PI*radius*radius;
        return c.area;
    }
};

class Rect:public Shape
{
private:
    int length;
    int width;

public:
    Rect(){cout<<"无参构造"<<endl;}

    Rect(int len,int wid):length(len),width(wid)
    {
        cout<<"有参构造"<<endl;
    }
    ~Rect()
    {
        cout<<"析构函数"<<endl;
    }
    double get_cir(Rect &r)
    {
        r.circumference=(length+width)*2;
        return r.circumference;
    }

    double get_area(Rect &r)
    {
        r.area=length*width;
        return r.area;
    }
};

int main()
{
    Circle c1(3);
    c1.get_cir(c1);
    c1.get_area(c1);
    c1.show();

    Rect r1(3,4);
    r1.get_cir(r1);
    r1.get_area(r1);
    r1.show();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值