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;
未完待续