重载赋值运算符详细

#include <iostream>
using namespace std;

class Date
{
	int y,m,d;
public:
	//构造
	Date(int y =1900,int m = 1,int d =1):y(y),m(m),d(d)
		  {
		  		cout << "Date(i,i,i) Constructor," << "this:" << this << endl;
		  }
	//拷贝构造
	Date(const Date& d)
	{
		y = d.y;
		m = d.m;
		this->d = d.d;
		cout << "Date(const Date& d) copy" << "this:" << this << endl;
	}
	//析构
	~Date()
	{
		cout << "~Date() Destructor," << "this:" << this << endl;
	}
};

class Emp
{
	string name;
	Date* birth;
	double salary;
public:
	//构造
	Emp(string n,int y, int m ,int d , double s):name(n),salary(s)
		  {
		  	birth = new Date(y,m,d);
			cout << "Emp(string,i,i,i,d) Constructor," << "this:" << this << endl;
		  }
	//拷贝构造
	Emp(const Emp& e)
	{
		cout << "Emp(const Emp& e) copy" << "this:" << this << endl;
		name = e.name;
		salary = e.salary;
		birth = new Date(*e.birth);  //拷贝来构造
	}
//	//重载赋值=
//	Emp& operator=(const Emp&e)
//	{
//		//修改此处
//		name = e.name;
//		//birth = e.birth;
//		//用的拷贝构造,还是有问题
//		birth = new Date(*e.birth);
//		salary = e.salary;
//		return *this;
//	}
	Emp& operator=(const Emp& e)
	{
		//比较完整的赋值重载,几乎是固定的。
		//1. 判断是否是自赋值
		//如果注释掉if语句,那么第三个阶段就会有问题
		if (this == &e)
		{
			return *this;
		}
		
		//2.释放原来的内存空间
		delete birth;

		//2.申请新的内存空间
		birth = new Date(*e.birth);

		//4.拷贝数据
		name = e.name;
		salary = e.salary;


		//5.返回当前对象
		return *this;
	}
	//析构
	~Emp()
	{
		delete birth;
		cout << "~Emp() Destructor," << "this:" << this << endl;
	}
};



int main()
{
	Emp e1("王五",2000,2,2,22222);   //构造
	Emp e2 = e1;  //拷贝构造
	Emp e3("",1,1,1,1);  //没有空参构造函数,Emp e3;  不行
	//第一个e3永远没有机会释放
	e3 = e1;  // e3.operator=(e1);
}
/*
Date(i,i,i) Constructor,this:0x9158020
Emp(string,i,i,i,d) Constructor,this:0xbfd4fb90
Emp(const Emp& e) copythis:0xbfd4fb80
Date(const Date& d) copythis:0x9158030
Date(i,i,i) Constructor,this:0x9158040
Emp(string,i,i,i,d) Constructor,this:0xbfd4fb70
~Date() Destructor,this:0x9158040
Date(const Date& d) copythis:0x9158040
~Date() Destructor,this:0x9158040
~Emp() Destructor,this:0xbfd4fb70
~Date() Destructor,this:0x9158030
~Emp() Destructor,this:0xbfd4fb80
~Date() Destructor,this:0x9158020
~Emp() Destructor,this:0xbfd4fb90
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值