喜欢的朋友可以关注收藏一下
本文提供了上周拷贝构造和拷贝赋值更规范的写法,避免了很多误操作。
一、拷贝构造
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;
}