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;
}
相关推荐
浪裡遊22 分钟前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
彭祥.1 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk1 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼1 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客2 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
程序员爱钓鱼2 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt
Frank学习路上2 小时前
【IOS】XCode创建firstapp并运行(成为IOS开发者)
开发语言·学习·ios·cocoa·xcode
2301_805054563 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
胖大和尚3 小时前
clang 编译器怎么查看在编译过程中做了哪些优化
c++·clang