004重載賦值運算符實現默認深拷貝操作

/*
 *c++編譯器至少給一個類添加4個函數
1. 默認構造函數(無參,函數體爲空)
2. 默認析構函數(無參,函數體爲空)
3. 默認拷貝構造函數,對屬性進行值拷貝
4. 賦值運算符 operator=, 對屬性進行值拷貝
如果類中有屬性指向堆區,做賦值操作時也會出現深淺拷貝問題
 */
//重載=運算符實現深拷貝
#include<iostream>
#include<string>
using namespace std;

class Person
{public:
	Person(int age)//將年齡數據開闢到堆區
	{
		m_Age = new int(age);//使用new關鍵字是在堆上分配的內存
	}

	//重載=運算符
	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);
		//返回本身
		return *this;
	}
	~Person()
	{
		if (m_Age!=NULL)
		{

			delete m_Age;
			m_Age = NULL;
		}
	}
	int *m_Age;//年齡的指針
};


int main(void)
{
	Person p1(19);
	Person p2(34);
	Person p3(34);
	p3 =p2= p1;

	cout << "p1d的年齡爲" << *p1.m_Age << endl;
	cout << "p2d的年齡爲" << *p2.m_Age << endl;
	cout << "p3d的年齡爲" << *p3.m_Age << endl;



	system("pause");
	return 0;
}

//不提供深拷貝當程序關閉的時候會3釋放三次內存宕機

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章