浅拷贝问题是学习C++时候常见的问题,形成这个问题的原因用代码和画图的方式呈现
#include "iostream"
using namespace std;
class Location
{
public:
Location(char *p) //一个参数的构造函数
{
m_len = strlen(p);
m_p = (char *)malloc(m_len + 1);
strcpy(m_p, p);
}
Location(const Location &obj) //深拷贝 拷贝构造函数 显示编写
{ //如果不显示编写,将会调用默认的拷贝构造函数进行浅拷贝
m_len = obj.m_len;
m_p = (char *)malloc(m_len + 1);
strcpy(m_p, obj.m_p);
}
void prinT()
{
cout << m_p << endl;
}
private:
char *m_p;
int m_len;
};
void main()
{
Location obj1("zhangwentao");
Location obj2 = obj1;
obj1.prinT();
obj2.prinT();
system("pause");
}