(GeekBand)C++面向?qū)ο蟾呒?jí)編程(上)第二周測(cè)試

第十三節(jié) 測(cè)試

#include<iostream>
using namespace std;

class Shape
{
public:
    Shape(){}
    virtual ~Shape(){}
    virtual void print()const =0;//打印
};      
class Point
{
public:
    int x;
    int y;
    Point(int _x,int _y):x(_x),y(_y)
    {}
};
class Rectangle:public Shape
{
    int width;
    int height;
    Point* leftUp;
public:
    Rectangle(int _width,int _height,int _x,int _y);//構(gòu)造
    Rectangle(const Rectangle& other);//拷貝構(gòu)造
    Rectangle& operator=(const Rectangle& other);//重載'='
    ~Rectangle();//析構(gòu)

    void print()const;
};
inline 
Rectangle::Rectangle(int _width,int _height,int _x,int _y):width(_width),height(_height),leftUp(new Point(_x,_y))
{
}
inline void 
Rectangle::print() const
{
    cout<<"width:"<<width<<",height:"<<height<<",Point("<<leftUp->x<<","<<leftUp->y<<")"<<endl;
}
inline 
Rectangle::Rectangle(const Rectangle& other)
{
    width=other.width;
    height=other.height;
    if(other.leftUp!=NULL)
        leftUp=new Point(other.leftUp->x,other.leftUp->y);
    else
    {
        delete leftUp;
        leftUp=NULL;
    }
}
inline Rectangle&
Rectangle::operator = (const Rectangle& other)
{
    if (this == &other)
    {
        return *this;
    }
   // delete leftUp;
    width = other.width;
    height = other.height;
    if(leftUp==NULL)//我空
    {
        //我空它空省略
        if(other.leftUp!=NULL)//我空它不空
        {
             leftUp = new Point(other.leftUp->x, other.leftUp->y);
        }
    }
    else//我不空
    {
        if(other.leftUp==NULL)//我不空它空
        {
            delete leftUp;
            leftUp=NULL;
        }
        else//我不空它不空
        {
            leftUp=new Point(*(other.leftUp));
        }
    }
    return *this;
}
inline 
Rectangle::~Rectangle()
{
    delete leftUp;
}
int main()
{
    Rectangle a(1,1,2,2);//構(gòu)造
    Rectangle b(a);//拷貝構(gòu)造
    Rectangle c(3,3,4,4);
    Rectangle d(0,0,0,0);
    d=c;//重載'='
    a.print();//打印
    b.print();
    c.print();
    d.print();
    return 0;
}

記錄學(xué)習(xí)點(diǎn)點(diǎn)滴滴。有興趣的關(guān)注我一起。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容