C++day5

发布于:2023-09-14 ⋅ 阅读:(129) ⋅ 点赞:(0)

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

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

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

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

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

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

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

#include <iostream>

#define PI 3.14



using namespace std;


class Shape
{
protected:
    double cir;//周长
    double area;//面积
public:
    Shape()//显性定义无参构造
    {
        cir = 0;
        area = 0;
       cout<<"无参构造函数"<<endl;
    }
    Shape(double cir, double area):cir(cir),area(area)
    {
        cout<<"有参构造函数"<<endl;
    }
    ~Shape()
    {
        cout<<"Shape::析构函数"<<endl;
    }
    Shape(const Shape &other):cir(other.cir),area(other.area)
    {
        cout<<"拷贝构造函数"<<endl;
    }
    Shape & operator=(const Shape &other)
    {
        this->cir = other.cir;
        this->area = other.area;
        cout<<"拷贝赋值函数"<<endl;
        return *this;
    }
};

class Circle:public Shape
{
private:
    double rad;
public:
    Circle()//显性定义无参构造
    {
        rad = 0;
       cout<<"无参构造函数"<<endl;
    }
    Circle(double rad):rad(rad)
    {
        cout<<"有参构造函数"<<endl;
    }
    ~Circle()
    {
        cout<<"Circle::析构函数"<<endl;
    }
    Circle(const Circle &other):rad(other.rad)
    {
        cout<<"拷贝构造函数"<<endl;
    }
    Circle & operator=(const Circle &other)
    {
        if(this != &other)
        {
           this->rad = other.rad;
        }
        cout<<"拷贝赋值函数"<<endl;
        return *this;
    }
    double get_cir()//获取周长函数
    {
        this->cir = 2*PI*rad;
        return this->cir;
    }
    double get_area()
    {
        this->area = PI*rad*rad;
        return this->area;
    }
};

class Rect:public Shape
{
private:
    double len;
    double width;
public:
    Rect()//显性定义无参构造
    {
        len = 0;
        width = 0;
       cout<<"无参构造函数"<<endl;
    }
    Rect(double len, double width):len(len),width(width)
    {
        cout<<"有参构造函数"<<endl;
    }
    ~Rect()
    {
        cout<<"Rect::析构函数"<<endl;
    }
    Rect(const Rect &other):len(other.len),width(other.width)
    {
        cout<<"拷贝构造函数"<<endl;
    }
    Rect & operator=(const Rect &other)
    {
        if(this != &other)
        {
            this->len = other.len;
            this->width = other.width;
        }
        cout<<"拷贝赋值函数"<<endl;
        return *this;
    }
    double get_cir()//获取周长函数
    {
        this->cir = 2*(len+width);
        return this->cir;
    }
    double get_area()
    {
        this->area = len*width;
        return this->area;
    }
};

int main()
{
   Circle c1(1.1);
   cout<<"c1周长="<<c1.get_cir()<<endl;
   cout<<"c1面积="<<c1.get_area()<<endl;

   Circle c2;
   c2 = c1;
   cout<<"c2周长="<<c1.get_cir()<<endl;
   cout<<"c2面积="<<c1.get_area()<<endl;

   Rect r1(2,3);
   cout<<"r1周长="<<r1.get_cir()<<endl;
   cout<<"r1面积="<<r1.get_area()<<endl;

   Rect r2 = r1;
   cout<<"r2周长="<<r1.get_cir()<<endl;
   cout<<"r2面积="<<r1.get_area()<<endl;
   return 0;
}

 


网站公告

今日签到

点亮在社区的每一天
去签到