1.代码
#include <iostream>
using namespace std;
class Person {
public:
Person() {}
//有参构造函数
Person(int age ,int height)
{
cout << "有参构造函数!" << endl;
m_age = age;
m_height = new int(height);
}
//拷贝构造函数
Person(const Person& p)
{
cout << "拷贝构造函数!" << endl;
//如果不利用深拷贝在堆区创建新内存,
//会导致浅拷贝带来的重复释放堆区问题
//m_age = p.m_age;
m_height = new int(*p.m_height);
}
//析构函数
~Person()
{
cout << "调用析构函数!" << endl;
if (m_height != NULL)
{
delete m_height;
}
}
public:
int m_age;
int* m_height;
};
void test01()
{
Person p1(18, 180);
Person p2(p1);
cout << "p1的年龄: " << p1.m_age << " 身高: " << *p1.m_height << endl;
cout << "p2的年龄: " << p2.m_age << " 身高: " << *p2.m_height << endl;
}
int main()
{
test01();
return 0;
}
2.分析
1.因为有参构造中,属性开辟在堆区了,
m_height = new int(height);
2.如果不重写拷贝构造,而使用编译器的拷贝构造,会出现问题的。
只会进行简单的值拷贝
Person(const Person& p)
{
cout << "拷贝构造函数!" << endl;
m_height = p.m_height;
}
两个指针,指向同一块内存空间。对象析构时,会重复释放内存,崩掉