C++ 类的继承特性简单运用

封装一个名为Shape(图形)的父类,从父类中派生两个子类,分别为Circle(圆形),Rect(矩形),父类拥有两个子类的共同特性,面积和周长,两个子类除了继承父类的共性,还需封装各自的成员属性

类的声明

#ifndef SHAPE_H
#define SHAPE_H

class Shape
{
protected:
    double per;
    double area;

public:
    Shape():per(0),area(0) {}
    Shape(double per, double area);
    Shape(const Shape& obj);

    ~Shape() {}
};


class Circle : public Shape
{
private:
    double radius;

public:
    Circle():Shape(0, 0), radius(0) {}
    Circle(double radius);
    Circle(const Circle& obj);

    double& Get_Per();
    double& Get_Area();

    ~Circle() {}
};

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

public:
    Rect():Shape(0, 0), length(0), width(0) {}
    Rect(double length, double width);
    Rect(const Rect &obj);

    double& Get_Per();
    double& Get_Area();

    ~Rect() {}
};

#endif // SHAPE_H

类的实现

#include "Shape.h"

Shape::Shape(double per, double area):per(0), area(0)
{
    this->per = per;
    this->area = area;
}

Shape::Shape(const Shape& obj)
{
    per = obj.per;
    area = obj.area;
}


Circle::Circle(double radius):Shape(0, 0), radius(0)
{
    this->radius = radius;
}

Circle::Circle(const Circle& obj)
{
    radius = obj.radius;
    per = obj.per;
    area = obj.area;
}

double& Circle::Get_Per()
{
    per = 2*3.14*radius;

    return per;
}

double& Circle::Get_Area()
{
    area = 3.14 * radius * radius;

    return area;
}


Rect::Rect(double length, double width):Shape(0, 0), length(0), width(0)
{
    this->length = length;
    this->width = width;
}

Rect::Rect(const Rect &obj)
{
    length = obj.length;
    width = obj.width;
    per = obj.per;
    area = obj.area;
}

double& Rect::Get_Per()
{
    per = 2 * (length + width);

    return per;
}

double& Rect::Get_Area()
{
    area = length * width;

    return area;
}

最终的效果图

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值