浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
//深拷贝与浅拷贝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(){//析构代码,将堆区开辟数据做释放操作if (m_Height != nullptr){delete m_Height;m_Height = nullptr;}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();system("pause");return 0;}
