c++继承

实现一个图形类(Shape),包含受保护成员属性:周长、面积,

公共成员函数:特殊成员函数书写

定义一个圆形类(Circle),继承自图形类,包含私有属性:半径

公共成员函数:特殊成员函数、以及获取周长、获取面积函数

定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度

公共成员函数:特殊成员函数、以及获取周长、获取面积函数

在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。

#include <iostream>
#define PI 3.14
using namespace std;
class Shape
{
protected:
    double permimeter;
    double area;
public:
    Shape()
    {
        cout<<"shape无参构造"<<endl;
    }
    Shape(double permimeter, double area):permimeter(permimeter),area(area)
    {
        cout<<"shape有参构造函数"<<endl;
    }
    ~Shape()
    {
        cout<<"shape析构函数"<<endl;
    }
    Shape(const Shape &other):permimeter(other.permimeter),area(other.area)
    {
        cout<<"shape拷贝构造函数"<<endl;
    }
    const Shape &operator=(const Shape &other)
    {
        this->permimeter = other.permimeter;
        this->area = other.area;
        cout<<"shape拷贝赋值函数"<<endl;
        return *this;
    }
    Shape(Shape && other):permimeter(other.permimeter),area(other.area)
    {
        cout<<"shape移动构造"<<endl;
    }
    Shape &operator=(Shape &&other)
    {
        this->area = other.area;
        this->permimeter = other.permimeter;
        return *this;
        cout<<"移动赋值 = "<<endl;
        return *this;
    }
};
class Circle:public Shape
{
private:
    double rad;
public:
    Circle()
    {
        cout<<"circle无参构造"<<endl;
    }
    Circle(double r):Shape(2*PI*r, PI*r*r),rad(r)
    {
        cout<<"circle有参构造"<<endl;
    }
    ~Circle()
    {
        cout<<"circle析构函数"<<endl;
    }
    Circle(const Circle &other):rad(other.rad)
    {
        cout<<"circle拷贝构造函数"<<endl;
    }
    double get_permimeter()
    {
        return permimeter;
    }
    double get_area()
    {
        return area;
    }
};
class Rect:public Shape
{
private:
    double length;
    double width;
public:
    Rect()
    {
        cout<<"rect无参构造"<<endl;
    }
    Rect(double l, double w):Shape(2*l+2*w, l*w),length(l),width(w)
    {
        cout<<"rect有参构造"<<endl;
    }
    ~Rect()
    {
        cout<<"rect析构函数"<<endl;
    }
    double get_permimeter()
    {
        return permimeter;
    }
    double get_area()
    {
        return area;
    }
};
int main()
{
    Circle c(3);
    cout<<"圆形面积 = "<<c.get_area()<<endl;
    cout<<"圆形周长 = "<<c.get_permimeter()<<endl;
    Rect r(4,5);
    cout<<"矩形周长 = "<<r.get_permimeter()<<endl;
    cout<<"矩形面积 = "<<r.get_area()<<endl;
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值