码迷,mamicode.com
首页 > 编程语言 > 详细

C++复制对象时勿忘每一部分

时间:2015-04-07 12:01:33      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:c++   拷贝构造   复制运算符   

确保两点: 1 复制所有的成员变量 2 调用所有基类的copy函数

class Customer
{
public:
	explicit Customer(const tstring _name,const tstring _lastTransaction)
		:m_sName(_name), m_sLastTransaction(_lastTransaction)
	{
		OutputDebugString(_T("Customer construct \n"));
	}
	virtual ~Customer(){
		OutputDebugString(_T("Customer deconstruct \n"));
	}
	
	Customer(const Customer& customer) : m_sName(customer.m_sName)
	{
		OutputDebugString(_T("Customer copy construct \n"));
	}
	Customer& operator=(const Customer& customer)
	{
		m_sName = customer.m_sName;
		OutputDebugString(_T("Customer operater \n"));
		return *this;
	}
private:
	tstring m_sName;
	tstring m_sLastTransaction;
};

class  PriorityCustomer: public Customer
{
public:
	explicit PriorityCustomer(const tstring name,const tstring lastTime,int nPriority):
		m_nPriority(nPriority), Customer(name, lastTime)
	{
		OutputDebugString(_T("PriorityCustomer construct \n"));
	}

	PriorityCustomer(const PriorityCustomer& rhs) :m_nPriority(rhs.m_nPriority),
		Customer(rhs)
	{
		OutputDebugString(_T("PriorityCustomer copy construct\n"));
	}

	PriorityCustomer& operator=(const PriorityCustomer rhs)
	{
		OutputDebugString(_T("PriorityCustomer operater \n"));
		m_nPriority = rhs.m_nPriority;
		Customer::operator=(rhs);
		return *this;
	}
	virtual ~PriorityCustomer(){
		OutputDebugString(_T("PriorityCustomer deconstruct \n"));
	}
private:
	int m_nPriority;
};

C++复制对象时勿忘每一部分

标签:c++   拷贝构造   复制运算符   

原文地址:http://blog.csdn.net/oshirdey/article/details/44917163

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!