• 浅拷贝:简单的赋值拷贝操作
  • 深拷贝:在堆区重新申请空间,进行拷贝操作 ```cpp

    include

    include

using namespace std;

// 深拷贝,浅拷贝

class Person { public: Person() { cout << “Person 的默认构造函数” << endl; }

  1. Person(int val, int height) {
  2. m_Height = new int(height);
  3. age = val;
  4. cout << "Person 的有参构造函数" << endl;
  5. }
  6. // 自己实现拷贝构造函数, 解决浅拷贝带来的问题
  7. Person(const Person& p) {
  8. cout << "Person 拷贝构造函数的调用" << endl;
  9. age = p.age;
  10. //m_Height = p.m_Height; // 编译器默认实现就是这行代码
  11. m_Height = new int(*p.m_Height);
  12. }
  13. ~Person() {
  14. // 析构代码,将堆区开辟的数据做释放操作
  15. if (m_Height != NULL) {
  16. delete m_Height;
  17. m_Height = NULL;
  18. }
  19. cout << "Person 的析构函数" << endl;
  20. }
  21. int age;
  22. int* m_Height; //身高

};

void test01() { Person p1(18, 160);

  1. cout << "p1的年龄为: " << p1.age << endl;
  2. cout << "p1的身高为: " << *p1.m_Height << endl;
  3. Person p2(p1);
  4. cout << "p2的年龄为: " << p2.age << endl;
  5. cout << "p2的身高为: " << *p2.m_Height << endl;

} int main() { test01(); system(“pause”); return 0; } ```

总结:如果有属性是在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题