浅拷贝
深拷贝与拷贝构造函数

浅拷贝
深拷贝与拷贝构造函数
#includeusing namespace std; //这样吧h1赋值给h2相当于是直接吧h1的地址直接复制一份给h2 class house { public: house(int area) { this->Area = area; pKey = malloc(area);// 向系统申请分配指定()里面大小个字节的内存空间, } ~house() { free(pKey); pKey = nullptr; }; void Where() const { std::cout << "Hello,I Live in" << pKey << std::endl; } private: void* pKey; //指向实际的房子 int Area; //房子面积 }; int main() { house h1(180); h1.Where(); house h2 = h1; h2.Where(); return 0; }
深拷贝与拷贝构造函数
#includeusing namespace std; //C++默认生成的拷贝构造函数,他的行为逻辑就是浅拷贝他只会复制一个一模一样的指针,并不会操作指针指向的东西 //想要实现我们的逻辑需求,就需要自定义拷贝构造函数,实现深拷贝 class house { public: house(const house&h) //添加一个拷贝构造函数 { this->Area = h.Area; pKey = malloc(h.Area);// 向系统申请分配指定()里面大小个字节的内存空间,并用free释放内存 } house(int area) { this->Area = area; pKey = malloc(area);// 向系统申请分配指定()里面大小个字节的内存空间, } ~house() { free(pKey); pKey = nullptr; }; void Where() const { std::cout << "Hello,I Live in" << pKey << std::endl; } private: void* pKey; //指向实际的房子 int Area; //房子面积 }; int main() { house h1(180); h1.Where(); house h2 = h1; h2.Where(); return 0; }