#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age,int height)
{
m_Age = age;
m_Height = new int(height);//new开辟出的空间是指针类型
cout << "Person的有参构造函数调用" << endl;
}
//自己实现拷贝构造函数 解决浅拷贝带来的问题
Person(const Person& p)
{
cout << "Person拷贝构造函数调用" << endl;
m_Age = p.m_Age;
//m_Height=p.m_Heiht;编译器默认实现就是这行代码
//深拷贝操作
m_Height = new int(*p.m_Height);
}
~Person()
{
//将堆区开辟的数据做释放操作
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "Person的有参构造函数调用" << endl;
}
int m_Age;
int* m_Height;
};
void test01()
{
Person p1(18, 160);
cout << "p1的年龄:" << p1.m_Age << "身高为:"<<*p1.m_Height<<endl;
Person p2 = p1;
cout << "p2的年龄:" << p2.m_Age << "身高为:"<<*p2.m_Height<<endl;
}
int main()
{
test01();
}
这里创建了两个对象p1与篇,若没有这行自己实现的拷贝构造函数,就会默认使用系统自带的拷贝构造函数,从而造成上图的空间重复释放的问题。
因此我们可以再向堆区申请一块空间,放入m_Height的值,再对该值指向的地址进行释放即可,因而要实现一个自己创建的拷贝构造函数,指向0x0022这一块空间。