下面代码正常运行
#include
using namespace std;
class Person
{
public:
Person(int age=0)
{
m_age = new int(age);
}
~Person()
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
}
friend ostream& operator<<(ostream& output, Person &p);
Person& operator=(Person& p);
private:
int* m_age;
};
ostream& operator<<(ostream& output, Person &p)
{
output << *p.m_age;
return output;
}
Person& Person:: operator=(Person& p)
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
m_age = new int(*p.m_age);
return *this;
}
void test01()
{
Person p1(19), p2(20);
p2 = p1;
cout << "p1=" << p1 << endl;
cout << "p2=" << p2 << endl;
}
int main()
{
test01();
}
可如果把输出流重载函数里第二个参数里的&去掉,代码就会出错
当你去掉参数中&
时,参数是按值拷贝,由于你没有实现拷贝构造函数,编译器会自动生成默认的拷贝构造函数,默认的拷贝构造函数只是简单地按位拷贝,即把成员变量指针m_age直接拷贝过去,这样实参和形参两个对象同时拥有m_age指针,当对象析构时,它们就试图释放m_age指针所指的内存,这就造成了对m_age指针释放两次错误。
解决这个问题,你可以添加自己的拷贝构造函数、或移动构造函数
你这里有很多错误
因为有int* mage这个变量的存在
operator= 中间必须判断是
a=a的形式,如果有将引起崩溃
Person& Person:: operator=(const Person& p)
{
if(this==&rh)
return *this;
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
if(m.m_page!=nullptr)
m_age = new int(*p.m_age);
return *this;
}