class MForwardInfo { public: MForwardInfo(MProjectInfo* info) :projectInfo(info) { ; } MForwardInfo() {}; ~MForwardInfo();QString name; QString describe; QStringList dataInfo[5]; MProjectInfo* projectInfo;} 给这个类进行深拷贝构造,并重载=号
时间: 2024-01-21 14:18:43 浏览: 64
拷贝构造函数和赋值操作符号的重载.docx
深拷贝构造函数:
```cpp
MForwardInfo::MForwardInfo(const MForwardInfo& other) {
name = other.name;
describe = other.describe;
for (int i = 0; i < 5; i++) {
dataInfo[i] = other.dataInfo[i];
}
projectInfo = new MProjectInfo(*other.projectInfo);
}
```
重载赋值运算符:
```cpp
MForwardInfo& MForwardInfo::operator=(const MForwardInfo& other) {
if (this == &other) {
return *this;
}
name = other.name;
describe = other.describe;
for (int i = 0; i < 5; i++) {
dataInfo[i] = other.dataInfo[i];
}
delete projectInfo;
projectInfo = new MProjectInfo(*other.projectInfo);
return *this;
}
```
需要注意的是,在进行深拷贝时,需要对类中指针类型的成员变量进行拷贝,而不是简单地复制指针地址。在实现中,我使用了MProjectInfo类的拷贝构造函数进行了拷贝。在重载赋值运算符时,需要先释放原有的资源,再进行深拷贝。同时,需要注意自我赋值的情况,避免出现内存泄漏。
阅读全文