喜歡的朋友可以關注收藏一下
本文提供了上週拷貝構造和拷貝賦值更規範的寫法,避免了很多誤操作。
一、拷貝構造
inline Rectangle::Rectangle(const Rectangle& other) : Shape(other),width(other.width), height(other.height) /*:leftUp(new Point(other.leftUp->get_x(), other.leftUp->get_y())) */ //深度拷貝,需要Point有構造函數
{
if (other.leftUp != nullptr) //如果拷貝的 指針leftUp 不爲空 ,拷貝構造他
{
this->leftUp = new Point(*(other.leftUp));
}
else //如果爲空,賦值 0
{
this->leftUp = nullptr; //指針0 c++11
}
}
二、拷貝賦值
inline Rectangle& Rectangle::operator=(const Rectangle& other) //拷貝賦值函數
{
if (this == &other) //左右重複 自我賦值
{
return *this;
}
else //左右不重複
{
Shape::operator=(other); //給父類拷貝賦值
this->width = other.width;
this->height = other.height;
if (this->leftUp != nullptr) //左不爲空
{
if (other.leftUp != nullptr) //左右都不爲空
{
*(this->leftUp) = *(other.leftUp); //???
}
else //左不空,右爲空
{
delete leftUp;
leftUp = nullptr;
}
}
else //左爲空
{
if (other.leftUp != nullptr) //左爲空,右不爲空
{
this->leftUp = new Point(*(other.leftUp));
}
else //左爲空,右爲空(不操作,等待返回)
{
;
}
}
return *this;
}