C++(day5)

思维导图

小练习

实现一个图形类(Shape),包含受保护成员属性:周长、面积,公共成员函数:特殊成员函数书写

定义一个圆形类(Circle),继承自图形类,包含私有属性:半径,公共成员函数:特殊成员函数、以及获取周长、获取面积函数

定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度,公共成员函数:特殊成员函数、以及获取周长、获取面积函数

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

cpp 复制代码
#include <iostream>

#define PI 3.14

using namespace std;

class Shape{
protected:
    double area;   //面积
    double round;  //周长
public:
    //无参构造
    Shape(){}
    //有参构造
    Shape(double a,double rd):area(a),round(rd){}
    //拷贝构造函数
    Shape(const Shape &other):area(other.area),round(other.round){}
    //析构函数
    ~Shape(){}
    void show(){
        cout<<"*******************"<<endl;
        cout<<"该图形的周长为"<<round<<endl;
        cout<<"该图形的面积为"<<area<<endl;
    }
};

class Circle:public Shape{
private:
    int radius;
public:
    //无参构造
    Circle(){}
    //有参构造
    Circle(int rs):radius(rs){}
    //拷贝构造函数
    Circle(const Circle &other):Shape(Shape(other.area,other.round)),radius(other.radius){}
    //析构函数
    ~Circle(){}
    //获取周长函数
    void get_round(){
        round=2*PI*radius;
    }
    //获取面积函数
    void get_area(){
        area=PI*radius*radius;
    }
};

class Rect:public Shape{
private:
    int length; //长度
    int width;  //宽度
public:
    //无参构造
    Rect(){}
    //有参构造
    Rect(int l,int w):length(l),width(w){}
    //拷贝构造函数
    Rect(const Rect &other):Shape(Shape(other.area,other.round)),length(other.length),width(other.width){}
    //析构函数
    ~Rect(){}
    //获取周长函数
    void get_round(){
        round=2*(length+width);
    }
    //获取面积函数
    void get_area(){
        area=length*width;
    }
};

int main()
{
    Circle c(5);
    c.get_round();
    c.get_area();
    c.show();
    Rect r(4,7);
    r.get_area();
    r.get_round();
    r.show();
    return 0;
}
相关推荐
крон31 分钟前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan1 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊1 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1182 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之2 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头3 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu3 小时前
java内存模型JMM
java·开发语言
利刃大大3 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面3 小时前
C++刷题:日期模拟(1)
c++·学习·算法