【Geekband】Homework 2

2016-03-15  本文已影响140人  读书行路风雨兼程

题目为 Rectangle 类实现构造函数,拷贝构造函数,赋值操作符,析构函数。

class Shape
{                  
   int no;
};             
class Point
{
   int x;
   int y;
};             
class Rectangle: public Shape
{
   int width;
   int height;
   Point * leftUp;
public:
   Rectangle(int width, int height, int x, int y);
   Rectangle(const Rectangle& other);
   Rectangle& operator=(const Rectangle& other);
   ~Rectangle();        
};

设计思路

01. Big Three Function Design - 三大函数设计

1.1 General Constructor - 构造函数
class MyClass
{
    // for private variables
public:
    // for public interface
protected:
    // for protected functions
}
Rectangle(int width, int height)
{
    this->width = width;
    this->height = height;  
}
// Class
class Point
{
   int x;
   int y;
public:
    Point (int x  = 0, int y =0)
    {
        this->x = x;
        this->y = y;
    }
    int get_x() const {return x;}
    int get_y() const {return y;}
};              
class Rectangle: public Shape
{
   int width;
   int height;
   Point* leftUp; 
public:
   Rectangle(int width, int height, int x, int y);
    ... 
};
// Constructor
Rectangle::Rectangle(int width, int height, int x, int y)
{
     this->width = width;
     this->height = height;
     this->leftUp = new Point(x, y);
}
1.2 Copy Constructor
Rectangle::Rectangle(const Rectangle& other):
    Shape(other),  // Step 1: father class member
    width_(other.width_),  // Step 2: non-pointer member
    height_(other.height_)
{ 
    if (other.leftUp_ != nullptr)  // Step 3: Check whether other is nullptr
    {
        this->leftUp_ = new Point(*(other.leftUp_));  // Point copy constructor; other.leftUp_ is a (Point* ); so *(other.leftUp_) is a Point.     
    }
    else
        this->leftUp_= nullptr;
}
1.3 Copy Assignment
Rectangle& Rectangle::operator=(const Rectangle& other)
{
    if (this == &other) // Step 1:  Self Assignment Check
    {
        return *this;
    }   
    Shape::operator=(other);    // Step 2: Default copy assignment
    this->width_ = other.width_;  // Step 3: General member variables copy
    this->height_ = other.height_; 
    if( other.leftUp_ != nullptr )   // Step 4: Check pointer member
    {
       if( this->leftUp_ != nullptr )
       {
          *(this->leftUp_) = *(other.leftUp_);
       }
       else
       {
          this->leftUp_ = new Point(*other.leftUp_);
       }
    }
    else
    {
       delete this->leftUp_;
       this->leftUp_ = nullptr;
    } 
    return *this;
}
1.4 Destructor
Rectangle::~Rectangle()
{
   delete leftUp;
}
Rectangle::~Rectangle()
{
   delete leftUp;  // Just release the memory space, but not the value is still an address
   leftUp = nullptr;
}
1.5 inline function
undefined reference to

总结

Reference

上一篇 下一篇

猜你喜欢

热点阅读