c++ 深拷贝代码
时间: 2023-07-09 15:08:45 浏览: 45
深拷贝是指在新的内存空间中创建一个与原对象完全相同的对象,两个对象之间没有任何关联。以下是 C++ 中进行深拷贝的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char* str;
public:
// 构造函数
MyString(const char* s = "") {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
// 拷贝构造函数
MyString(const MyString& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
// 赋值运算符重载
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] str;
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
return *this;
}
// 析构函数
~MyString() {
delete[] str;
}
};
```
在上面的代码中,我们使用了拷贝构造函数和赋值运算符重载来实现深拷贝。在拷贝构造函数中,我们首先为新的对象分配内存,然后将原对象的数据复制到新对象中;在赋值运算符重载中,我们首先判断是否是自我赋值,如果不是,则释放当前对象的内存空间,然后为新的对象分配内存,并将原对象的数据复制到新对象中。最后,在析构函数中,我们释放了动态分配的内存空间。