9.12 C++作业

本文介绍了如何在C++中使用面向对象编程创建图形类Shape,以及其子类Circle(基于半径)和Rect(基于长度和宽度),展示了构造函数、析构函数和成员函数的使用,包括计算周长和面积。

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

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

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

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

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

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

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

#include <iostream>

using namespace std;


class Shape
{
protected:
    double c;    //周长
    double s;    //面积

public:
    Shape(){cout<<"无参构造函数"<<endl;}
    Shape(double c1, double s1):c(c1), s(s1)
    {
        cout<<"有参构造函数"<<endl;
    }

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

    //拷贝构造
    Shape(const Shape &other):c(other.c), s(other.s)
    {
        cout<<"拷贝构造"<<endl;
    }

};

//定义一个圆形类
class Circle:public Shape
{
private:
    double r;    //半径

public:
    Circle(){cout<<"无参构造函数"<<endl;}
    Circle(double c1, double s1, double r1):Shape(c1, s1), r(r1)
    {
        cout<<"有参构造函数"<<endl;
    }

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

    //拷贝构造
    Circle(const Circle &other):Shape(other.c, other.s), r(other.r)
    {
        cout<<"拷贝构造"<<endl;
    }

    //获取周长
    void get_c(double r)
    {
         c = 2*r*3.14;
         cout<<"该圆的周长为"<<c<<endl;
    }

    //获取面积
    void get_s(double r)
    {
        s = 2*r*r*3.14;
        cout<<"该圆的面积为"<<s<<endl;
        cout<<endl;
    }
};


//定义一个矩形类
class Rect:public Shape
{
private:
    double h;    //高
    double w;    //宽

public:
    Rect(){cout<<"无参构造函数"<<endl;}
    Rect(double c1, double s1, double h1, double w1):Shape(c1, s1), h(h1), w(w1)
    {
        cout<<"有参构造函数"<<endl;
    }

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

    //拷贝构造
    Rect(const Rect &other):Shape(other.c,other.s), h(other.h), w(other.w)
    {
        cout<<"拷贝构造"<<endl;
    }

    //获取周长
    void get_c(double h,double w)
    {
         c = 2*(h+w);
         cout<<"该矩形的周长为"<<c<<endl;
    }

    //获取面积
    void get_s(double h, double w)
    {
        s = h*w;
        cout<<"该矩形的面积为"<<s<<endl;
        cout<<endl;
    }
};

int main()
{
    Circle a;    //圆类对象
    a.get_c(5);  //圆周长
    a.get_s(5);  //圆面积

    Rect b;       //矩形类对象
    b.get_c(4,5); //周长
    b.get_s(4,5); //面积
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值