9.12 C++作业

实现一个图形类(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;
}
相关推荐
小溪学编程32 分钟前
从 C++ 的规范变迁看语言发展
jvm·c++·面试
ShineWinsu1 小时前
对于Redis:string类型的解析
java·c++·redis·分布式·缓存·面试·string
YYYing.2 小时前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
高山有多高3 小时前
【Linux笔记】Linux自定义Shell
linux·c++
悠仁さん3 小时前
【C++】vector 类
开发语言·c++
_upupup4 小时前
智能指针的原理及简单模拟实现(C++)
开发语言·c++
l1t4 小时前
DeepSeek总结的OpenZL压缩变换器
c++·算法
郝学胜-神的一滴4 小时前
C++ Templates 01:拨开迷雾,读懂C++模板经典著作
开发语言·c++·程序人生·游戏·游戏引擎·软件构建
坤坤子吖4 小时前
算法学习——高精度加减乘除
c++·笔记·学习·算法
朝朝辞暮i4 小时前
C++ 第 14 课:引用 &
开发语言·c++·算法