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;
}
传值 不是创建一份 p1 的复制品
复制的p1 中的m_p 的指向 也是堆区的那块空间
解引用赋值到 p2创建的空间上 ( this->m_p = new int(*p.m_p);)
为啥输出的不是10 而是随机数
对两种写法的 p2 = p1 语句分类讨论:
person(person const &p) // 产生临时对象所调用的复制构造函数
{
this->m_p = p.m_p;
}
先去掉赋值语句打印看看内容。