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;
}
相关推荐
风吹迎面入袖凉3 分钟前
【Redis】Redisson分布式锁原理
java·服务器·开发语言
A.A呐4 分钟前
【QT第五章】系统相关
开发语言·qt
Mapleay7 分钟前
CLion IDE 使用
c++
李白你好9 分钟前
Java GUI-未授权漏洞检测工具
java·开发语言
兵哥工控12 分钟前
MFC用高精度计时器实现五段时序控制的改进
c++·mfc
leo__52024 分钟前
拉丁超立方抽样(Latin Hypercube Sampling, LHS)MATLAB实现
开发语言·matlab
会编程的土豆24 分钟前
日常做题 vlog
数据结构·c++·算法
sycmancia26 分钟前
Qt——Qt中的标准对话框
开发语言·qt
22信通小白28 分钟前
USRP初学者使用手册(基础配置及bug记录)——Linux+Clion(单台X310收发)
linux·运维·c++·5g·bug·信息与通信
橙露43 分钟前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化