C++ day5

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

#include <iostream>

using namespace std;

class Shape
{
protected:
    double round;          //周长
    double area;           //面积
public:
    //构造函数
    Shape() {cout<<"无参构造"<<endl;}
    Shape(int r, int a):round(r), area(a)
    {
        cout<<"有参构造"<<endl;
    }

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

    //拷贝构造函数
    Shape(const Shape &other):round(other.round), area(other.area)
    {
        cout<<"拷贝构造"<<endl;
    }

};

class Circle:public Shape
{
private:
    int radius;         //半径
public:
    //构造函数
    Circle() {cout<<"无参构造"<<endl;}
    Circle(int r):radius(r)
    {
        cout<<"有参构造"<<endl;
    }

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

    //拷贝构造函数
    Circle(const Circle &other): radius(other.radius)
    {
        cout<<"拷贝构造"<<endl;
    }

    //获取周长函数
    double get_round()
    {
        round = 2*3.14*radius;
        return round;
    }

    //获取面积函数
    double get_area()
    {
        area = radius * radius * 3.14;
        return area;
    }

    void show()
    {
        cout<<"Rect::radius = "<<radius<<endl;
        cout<<"Circle::round = "<<get_round()<<endl;
        cout<<"Circle::area = "<<get_area()<<endl;
    }
};

class Rect:public Shape
{
private:
    int height;     //长度
    int width;      //宽度
public:
    //构造函数
    Rect() {cout<<"无参构造"<<endl;}
    Rect(int h, int w):height(h), width(w)
    {
        cout<<"有参构造"<<endl;
    }

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

    //拷贝构造函数
    Rect(const Rect &other):height(other.height), width(other.width)
    {
        cout<<"拷贝构造"<<endl;
    }

    //获取周长函数
    double get_round()
    {
        round = (width + height) * 2;
        return round;
    }

    //获取面积函数
    double get_area()
    {
        area = width * height;
        return area;
    }

    void show()
    {
        cout<<"Rect::width = "<<width<<endl;
        cout<<"Rect::height = "<<height<<endl;
        cout<<"Rect::round = "<<get_round()<<endl;
        cout<<"Rect::area = "<<get_area()<<endl;
    }
};

int main()
{
    Circle c1(3);
    c1.show();

    Rect r1(3,4);
    r1.show();


    return 0;
}

运行结果为:

无参构造
有参构造
Rect::radius = 3
Circle::round = 18.84
Circle::area = 28.26
无参构造
有参构造
Rect::width = 4
Rect::height = 3
Rect::round = 14
Rect::area = 12
析构函数
析构函数
析构函数
析构函数

2、思维导图

猜你喜欢

转载自blog.csdn.net/Lychee_z23/article/details/132840053