问题遇到的现象和发生背景
class person{
public:
person(int a)
{
m_p = new int(a);
}
~person()
{
if(m_p != NULL)
{
delete m_p;
m_p = NULL;
}
}
int *m_p;
void operator=(person p)
{
if(this->m_p != NULL)
{
delete this->m_p;
this->m_p = NULL;
}
this->m_p = new int(*p.m_p);
}
};
void text1()
{
person p1(10);
person p2(20);
p2 = p1;
cout<<"p1.age="<<*p1.m_p<<endl;
cout<<"p2.age="<<*p2.m_p<<endl;
}
cout<<"p1.age="<<*p1.m_p<<endl; 输出一串数字 而不是 10
void operator=(person p) 写成 void operator=(person & p) 就可以正常运行
传值 不是创建一份 p1 的复制品
复制的p1 中的m_p 的指向 也是堆区的那块空间
解引用赋值到 p2创建的空间上 ( this->m_p = new int(*p.m_p);)
为啥输出的不是10 而是随机数