Simple use of inheritance features of C++ classes

Encapsulate a parent class named Shape (Graphic), and derive two subclasses from the parent class, namely Circle (circle) and Rect (rectangle). The parent class has the common characteristics of the two subclasses, area and perimeter. In addition to inheriting the common features of the parent class, subclasses also need to encapsulate their respective member attributes.

Class declaration

#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

Class implementation

#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;
}

final renderings

Insert image description here

Guess you like

Origin blog.csdn.net/m0_72847002/article/details/132839165