C++构造函数之深度复制(deep copy)

C++字符串作为类成员时,直接的复制很可能导致两个指针指向同一内存区域,析构时将引发未知错误

本文介绍下处理方法:

#ifndef INHERITANCE_H_
#define INHERITANCE_H_
#include <iostream>
using namespace std;
class Father
{
	
public:

	Father(char* str="NoName");//默认构造函数显示声明
    Father(const Father& f);//默认复制构造函数显示声明,必须显示声明,进行深度复制才能解决多个指针指向同一内存区域的问题
	virtual~Father();
	static int m_nCount;//静态成员,记录当前对象的数目
	void ShowCount()const;//显示当前对象数目
	void Show()const;//显示当前对象的信息
	friend ostream& operator<<(ostream& os,Father& f);
private:
	char* pName;//对象名
	int m_nLength;//对象名的长度

};
int Father::m_nCount=0;
ostream& operator<<(ostream& os,const Father& f)
{
	f.Show();
	return os;
}
Father::Father(char* str):pName(NULL)
{
	cout<<"Father类的默认构造函数被调用"<<endl;
	m_nCount++;
	m_nLength=strlen(str);
	if(m_nLength==0)
	{
		pName="NoName";
		return;
	}
	pName=new char[m_nLength+1];
	strcpy(pName,str);//strncpy,memcpy等也可以实现
}
Father::Father(const Father& f)//深度复制deep copy
{
	cout<<"Father类的复制构造函数被调用"<<endl;
	m_nCount++;
	m_nLength=f.m_nLength;
	pName=new char[m_nLength+1];
	strcpy(pName,f.pName);
}
Father::~Father()
{
	cout<<"Father类的析构函数被调用"<<endl;
	m_nCount--;
}
void Father::Show()const
{
	cout<<"当前对象名是:"<<pName<<endl;
	cout<<"对象名长度为:"<<m_nLength<<endl;
}
void Father::ShowCount()const
{
	cout<<"当前对象数目为:"<<m_nCount<<endl;
}

#endif;

未完待续

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值