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;
}
相关推荐
weixin_4461224620 分钟前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊23 分钟前
Python之--基本知识
开发语言·前端·python
QuantumStack1 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6731 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext2 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
代码的奴隶(艾伦·耶格尔)2 小时前
后端快捷代码
java·开发语言
Jay_5153 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
路来了3 小时前
Python小工具之PDF合并
开发语言·windows·python
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
WJ.Polar4 小时前
Python数据容器-list和tuple
开发语言·python