C++ 赋值运算符重载

C++ 赋值运算符重载

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

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝
    如果类中有属性指向堆区,做赋值操作时,也会出现深浅拷贝的问题

二、示例
1、浅拷贝

#include <iostream>
#include <string>

using namespace std;

class Persion
{
public:
	Persion(int age)
	{
		m_pAge = new int(age);
	}

	int *m_pAge;
};

void test01()
{
	Persion p1(18);
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 18
	Persion p2(20);
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 20
	
	p1 = p2;
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 20
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 20
}

int main()
{
	test01();
	system("pause");
	return 0;
}

释放内存会出问题:

#include <iostream>
#include <string>

using namespace std;

class Persion
{
public:
	Persion(int age)
	{
		m_pAge = new int(age);
	}
	// 加入析构函数   程序奔溃
	~Persion()
	{
		if (m_pAge)
		{
			delete m_pAge;
			m_pAge = nullptr;
		}
	}

	int *m_pAge;
};

void test01()
{
	Persion p1(18);
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 18
	Persion p2(20);
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 20
	
	p1 = p2;
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 20
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 20
}

int main()
{
	test01();
	system("pause");
	return 0;
}

浅拷贝会导致程序奔溃,原因是m_pAge 这个指针释放了2次,那么怎么解决呢?
使用深拷贝
在这里插入图片描述
在这里插入图片描述

示例:

#include <iostream>
#include <string>

using namespace std;

class Persion
{
public:
	Persion(int age)
	{
		m_pAge = new int(age);
	}

	~Persion()
	{
		if (m_pAge)
		{
			delete m_pAge;
			m_pAge = nullptr;
		}
	}
	Persion& operator=(const Persion& p)
	{
		// 编译器提供的是浅拷贝
		//m_pAge = p.m_pAge;

		// 我们要写深拷贝
		// 先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝
		if (m_pAge)
		{
			delete m_pAge;
			m_pAge = nullptr;
		}
		// 深拷贝
		m_pAge = new int(*p.m_pAge);
		// 返回对象本身
		return *this;
	}

	int *m_pAge;
};

void test01()
{
	Persion p1(18);
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 18
	Persion p2(20);
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 20
	Persion p3(25);
	cout << "p3的年龄为:" << *p3.m_pAge << endl;    // 25
	
	p1 = p2 = p3;
	cout << "p1的年龄为:" << *p1.m_pAge << endl;    // 25
	cout << "p2的年龄为:" << *p2.m_pAge << endl;    // 25
	cout << "p3的年龄为:" << *p3.m_pAge << endl;    // 25
}

int main()
{
	test01();
	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值