C++继承相关应用练习

1、

实现一个图形类(Shape),包含受保护成员属性:周长、面积,

公共成员函数:特殊成员函数书写

定义一个圆形类(Circle),继承自图形类,包含私有属性:半径

公共成员函数:特殊成员函数、以及获取周长、获取面积函数

定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度

公共成员函数:特殊成员函数、以及获取周长、获取面积函数

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

#include <iostream>
#include <cmath>

#define PI acos(-1)
using namespace std;


//图形类
class Shape
{
protected:
    int Zc;  //周长
    int Mj;  //面积

public:
    //无参
    Shape()
    {
        cout<<"无参构造函数"<<endl;
    }

    //有参
    Shape(int z,int m):Zc(z),Mj(m)
    {
        cout<<"有参构造函数"<<endl;
    }

    //析构函数
    ~Shape()
    {
        cout<<"析构函数"<<endl;
    }

    //拷贝函数
    Shape(const Shape &other):Zc(other.Zc),Mj(other.Mj)
    {
        cout<<"有参构造函数"<<endl;
    }

    void show()
    {
        cout<<"周长为:"<<Zc<<endl;
        cout<<"面积为:"<<Mj<<endl;
    }
};

//圆形类
class Circle:public Shape
{
private:
    int Bj;  //半径

public:
    //无参
    Circle()
    {
        cout<<"无参构造函数"<<endl;
    }

    //有参
    Circle(int z,int m,int b):Shape(z,m),Bj(b)
    {
        cout<<"有参构造函数"<<endl;
    }

    //析构函数
    ~Circle()
    {
        cout<<"析构函数"<<endl;
    }

    //拷贝函数
    Circle(const Circle &other):Shape(other.Zc,other.Mj),Bj(other.Bj)
    {
       cout<<"有参构造函数"<<endl;
    }

    //获取周长
    void get_zhouchang()
    {
        Zc=2*PI*Bj;
    }

    //获取面积
    void get_mianji()
    {
        Mj=PI*(pow(Bj,2));
    }

};

//矩形类
class Rect:public Shape
{
private:
    int Cd;  //长度
    int Kd;  //宽度
public:
    //无参
    Rect()
    {
        cout<<"无参构造函数"<<endl;
    }

    //有参
    Rect(int z,int m,int c,int k):Shape(z,m),Cd(c),Kd(k)
    {
        cout<<"有参构造函数"<<endl;
    }

    //析构函数
    ~Rect()
    {
        cout<<"析构函数"<<endl;
    }

    //拷贝函数
    Rect(const Rect &other):Shape(other.Zc,other.Mj),Cd(other.Cd),Kd(other.Kd)
    {
        cout<<"有参构造函数"<<endl;
    }

    //获取周长
    void get_zhouchang()
    {
        Zc=(Cd+Kd)*2;
    }

    //获取面积
    void get_mianji()
    {
        Mj=Cd*Kd;
    }

};

int main()
{   
    //圆形
    Circle C1(0,0,6);
    C1.get_zhouchang();
    C1.get_mianji();
    C1.show();

    //矩形
    Rect R1(0,0,3,4);
    R1.get_zhouchang();
    R1.get_mianji();
    R1.show();

    return 0;
}

2、思维导图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值