【原创】C++_第二周_Rectangle类的初步实现(一)(修订)之拷贝构造和拷贝赋值规范写法

本文详细介绍了拷贝构造函数及拷贝赋值运算符的实现方式,并通过具体示例解释了如何进行深度拷贝及正确处理成员指针的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

喜欢的朋友可以关注收藏一下

本文提供了上周拷贝构造和拷贝赋值更规范的写法,避免了很多误操作。

一、拷贝构造

 

	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;
		}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值