我在学习黑马的C++的重载运算符operator=时,按照它的要求
#include <iostream>
using namespace std;
class Person
{
friend ostream &operator<<(ostream &cout, Person p);
public:
Person(int age, double height);
~Person();
Person &operator=(Person &p);
private:
int m_age;
double m_height;
int *m_grade;
};
Person::Person(int age, double height)
{
m_age = age;
m_height = height;
m_grade = new int(100);
}
Person::~Person()
{
if (m_grade != NULL)
{
delete m_grade;
m_grade = NULL;
}
}
ostream &operator<<(ostream &cout, Person p)
{
cout << "age=" << p.m_age << "\t"
<< "height=" << p.m_height << "\tgrade=" << *p.m_grade;
return cout;
}
Person &Person::operator=(Person &p)
{
this->m_age = p.m_age;
this->m_height = p.m_height;
if (this->m_grade != NULL)
{
delete this->m_grade;
this->m_grade = NULL;
}
this->m_grade = new int(*p.m_grade);
return *this;
}
int main()
{
Person p1(19, 179.8);
Person p2(15, 170);
p2 = p1;
cout << p2 << endl;
return 0;
}
在delete处崩溃,猜测是重复释放
我认真考虑了是不是重复释放,可是我认为我重载没问题
正常运行
friend ostream &operator<<(ostream &cout, Person &p); //Person &p,不用引用,这里调用一次析构函数
Person &Person::operator=(Person &p)
{
this->m_age = p.m_age;
this->m_height = p.m_height;
if (this->m_grade != NULL) //没必要删了重新new
{
// delete this->m_grade;
*(this->m_grade) = *p.m_grade;
}
else
this->m_grade = new int(*p.m_grade);
return *this;
}