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;
}
相关推荐
m0_662577972 分钟前
C++中的模板方法模式
开发语言·c++·算法
m0_748873551 小时前
C++与Rust交互编程
开发语言·c++·算法
2401_891482179 小时前
多平台UI框架C++开发
开发语言·c++·算法
无敌昊哥战神9 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
Darkwanderor10 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_8319207410 小时前
分布式系统安全通信
开发语言·c++·算法
2401_8772742410 小时前
从匿名管道到 Master-Slave 进程池:Linux 进程间通信深度实践
linux·服务器·c++
汉克老师11 小时前
GESP5级C++考试语法知识(八、链表(三)循环链表)
c++·约瑟夫问题·循环链表·gesp5级·gesp五级
阿贵---11 小时前
C++中的RAII技术深入
开发语言·c++·算法
PiKaMouse.11 小时前
navigation2-humble从零带读笔记第一篇:nav2_core
c++·算法·机器人