简言之,
浅拷贝就是两个对象中的指针数据类型指向了同一个内存地址
深拷贝就是为被赋值对象申请了一个新的内存
如下如程序所示:
浅拷贝:
lass string
{
char *m_str;
public:
string(char *s)
{
m_str=s;
}
string(){};
string&operator=(const string s)
{
m_str=s.m_str;
return *this}
};
int main()
{
string s1("abc"),s2;
s2=s1;
cout<<s2.m_str;
}
深拷贝(修改赋值函数即可):
string &operator=(const string &s)
{
if (strlen(m_str) != strlen(s.m_str))
{
m_str = new char[strlen(s.m_str)+1];
}
if (this != &s)
{
strcpy(m_str,s.m_str);
}
return *this;
}