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;
}
相关推荐
AMoon丶2 分钟前
C++基础-类、对象
java·linux·服务器·c语言·开发语言·jvm·c++
为搬砖记录5 分钟前
杰理AC695N soundbox 3.1.2打开ble宏的编译bug
c语言·开发语言·单片机·bug
17(无规则自律)13 分钟前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode·哈希算法
样例过了就是过了15 分钟前
LeetCode热题100 子集
数据结构·c++·算法·leetcode·dfs
y = xⁿ27 分钟前
【Java八股锁机制的认识】synchronized和reentrantlock区分,锁升级机制
java·开发语言·后端
Fruit_Caller28 分钟前
GmSSL 编译与 Qt 项目集成问题排查记录(-lssl-1_1-x64 -lcrypto-1_1-x64)
开发语言·qt
free-elcmacom28 分钟前
C++三种参数传递方式:从交换函数看值、指针与引用的区别
开发语言·c++
bubiyoushang88831 分钟前
基于PSO的列车速度优化MATLAB实现
开发语言·人工智能·matlab
柏木乃一33 分钟前
Linux线程(8)基于单例模式的线程池
linux·运维·服务器·c++·单例模式·操作系统·线程
曹牧40 分钟前
C#:线程中实现延时等待
开发语言·c#