C++赋值运算符重载

c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

cpp 复制代码
#include<iostream>
using namespace std;

class Person {
public:
	Person(int age) {
		//将年龄数据开辟到堆区
		m_Age = new int(age);
	}
	//重载赋值运算符
	Person& operator=(Person& p)
	{
		//应该先判断是否属性再堆区,如果有先释放干净,然后再深拷贝 
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
		//编译器提供的代码是浅拷贝
		//m_Age = p.m_Age;
		
		//提供深拷贝 解决浅拷贝的问题
		m_Age = new int(*p.m_Age); //*p.m_Age

		//返回自身
		return *this;  //this =Person operator=
	}
	~Person()
	{
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
	}
	int *m_Age;
};

void test01()
{
	Person p1(18);
	Person p2(20);
	Person p3(30);

	p3 = p2 = p1;  //赋值
	
	cout << "p1的年龄为:" << *p1.m_Age << endl;
	cout << "p2的年龄为:" << *p2.m_Age << endl;
	cout << "p3的年龄为:" << *p3.m_Age << endl;

}

int main()
{
	//test01();
	test01();
	return 0;
}
相关推荐
mjhcsp13 小时前
根号快速计算牛顿迭代法
开发语言·c++·算法·迭代法
jiayong2313 小时前
第 41 课:任务详情抽屉里的快速筛选联动
开发语言·前端·javascript·vue.js·学习
xiaoshuaishuai813 小时前
【无标题】
开发语言·windows·c#
小小de风呀14 小时前
de风——【从零开始学C++】(二):类和对象入门(一)
开发语言·c++
浅念-14 小时前
LeetCode 模拟算法:用「还原过程」搞定编程题的入门钥匙
开发语言·c++·学习·算法·leetcode·职场和发展·模拟
澈20714 小时前
C++面向对象编程:从封装到实战
开发语言·c++
无敌昊哥战神14 小时前
【LeetCode 491】递增子序列:不能排序怎么去重?一文讲透“树层去重”魔法!
c语言·c++·python·算法·leetcode
巨量HTTP14 小时前
Python 获取动态 iframe 内容(完整解决方案)
开发语言·python
Queenie_Charlie14 小时前
关于二叉树
数据结构·c++·二叉树
王江奎14 小时前
Windows 跨平台 C/C++ 项目中的 UTF-8 路径陷阱
c++·windows·跨平台