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;
}
相关推荐
2301_771717211 分钟前
Java自定义注解创建详解
java·开发语言
小陈工5 分钟前
Python Web开发入门(十二):使用Flask-RESTful构建API——让后端开发更优雅
开发语言·前端·python·安全·oracle·flask·restful
艾莉丝努力练剑7 分钟前
【Linux系统:信号】线程安全不等于可重入:深度拆解变量作用域与原子操作
java·linux·运维·服务器·开发语言·c++·学习
笑鸿的学习笔记8 分钟前
Qt与CMake笔记之option、宏传递与Qt Creator项目设置
开发语言·笔记·qt
楼田莉子8 分钟前
同步/异步日志系统:日志的工程意义及其实现思想
linux·服务器·开发语言·数据结构·c++
无心水9 分钟前
20、Spring陷阱:Feign AOP切面为何失效?配置优先级如何“劫持”你的设置?
java·开发语言·后端·python·spring·java.time·java时间处理
kpl_209 分钟前
特殊类设计、类型转换和IO流(C++)
c++
牢姐与蒯11 分钟前
栈和队列的实现
c++
cccyi712 分钟前
【C++ 脚手架】brpc 的介绍与使用
c++·rpc·brpc
0xDevNull13 分钟前
Java 21 新特性概览与实战教程
java·开发语言·后端