#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);
cout<<"Person的有参构造函数"<<endl;
}
//自己实现拷贝构造函数,解决浅拷贝带来的问题
Person(const Person &p)
{
cout<<"Person拷贝构造函数调用"<<endl;
m_Age=p.m_Age;
//m_Height=p.m_Height;编译器默认实现的这行代码(浅拷贝)
//深拷贝的操作
m_Height=new int(*p.m_Height);
}
~Person()
{
//析构代码,将堆区开辟数据做释放操作,如果不自己实现拷贝构造函数,
//此处浅拷贝会出错:
//m_Height指针被分配一次内存,析构函数会被调用两次,
//内存被释放两次,会造成内存泄漏
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的身高为:"<<*p1.m_Height<<endl;
Person p2(p1);
cout<<"p2的年龄为:"<<p2.m_Age<<" p2的身高为:"<<*p2.m_Height<<endl;
}
//如果用户定义有参构造函数,C++就不再提供无参构造函数,但是会提供默认拷贝构造函数
//如果用户定义拷贝构造函数,C++就不会再提供其他构造函数
//如果有属性在堆区开辟的,一定要自己提供拷贝函数,防止浅拷贝带来的问题
int main()
{
test01();
system("pause");
return 0;
}
C++中的浅拷贝与深拷贝
于 2020-06-07 22:36:36 首次发布