封装一个名为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;
}