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;
}
相关推荐
一人の梅雨9 分钟前
1688 店铺商品全量采集与智能分析:从接口调用到供应链数据挖掘
开发语言·python·php
小何好运暴富开心幸福20 分钟前
C++之日期类的实现
开发语言·c++·git·bash
威风的虫35 分钟前
JavaScript中的axios
开发语言·javascript·ecmascript
老赵的博客40 分钟前
c++ 是静态编译语言
开发语言·c++
Terio_my40 分钟前
Python制作12306查票工具:从零构建铁路购票信息查询系统
开发语言·python·microsoft
消失的旧时光-19431 小时前
Kotlin when 用法完整分享
android·开发语言·kotlin
万粉变现经纪人1 小时前
如何解决 pip install -r requirements.txt 约束文件 constraints.txt 仅允许固定版本(未锁定报错)问题
开发语言·python·r语言·django·beautifulsoup·pandas·pip
Fairy_sevenseven1 小时前
[1]python爬虫入门,爬取豆瓣电影top250实践
开发语言·爬虫·python
lixinnnn.2 小时前
贪心:火烧赤壁
数据结构·c++·算法
珹洺2 小时前
Java-Spring入门指南(二十一)Thymeleaf 视图解析器
java·开发语言·spring