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;
}
相关推荐
qq_3391911413 分钟前
go cpu占比高排查,cpu100%排查,go pprof cpu命令
开发语言·后端·golang
西西弗Sisyphus17 分钟前
Qt 配置文件图标和文件版本信息
开发语言·qt
秋田君25 分钟前
Qt_Qt(c++)开发中常见错误与解决方法
开发语言·c++·qt
夏霞42 分钟前
c# 不支持的目标框架 解决方案
开发语言·c#
雄哥0071 小时前
java代码反编译CFR
java·开发语言·反编译·cfr
lsylalalala1 小时前
多线程(2)
java·开发语言·多线程
星恒随风1 小时前
C++11详解(一):统一初始化——列表初始化与 initializer_list
c++·笔记·学习·list·状态模式
jimy11 小时前
右值大类rvalue的xvalue,和 左值大类glvalue的xvalue的区别
开发语言·c++
影视飓风TIM1 小时前
C++哈希表:unordered_set / unordered_map底层原理
c++·算法·哈希算法·散列表
geovindu1 小时前
CSharp: Template Method Pattern
开发语言·后端·c#·.net·模板方法模式·行为模式