C++复制构造函数和 = 运算符重载
C++ Copy Constructor and = operator overloading
我正在尝试在C++中了解复制构造函数,运算符重载和析构函数。给定一个包含指向其自身类型的指针的类,如何编写复制构造函数或 = 运算符重载?我已经尝试了以下内容,但是在main中声明或分配测试对象时,我不断遇到分段错误。谁能解释我做错了什么?
class Test {
public:
Test(string name);
Test(const Test& testObject);
Test& operator=(const Test& rhs);
~Test();
string getName();
void setName(string newname);
Test* getNeighbor(int direction);
void setNeighbor(Test* newTest, int direction);
private:
string name;
Test* neighbors[4];
};
Test::Test() {
name = "*";
neighbors[4] = new Test[4];
}
Test::Test(const Test& testObject) {
this->name = testObject.name;
for (int i = 0; i < 4; i++) {
this->neighbors[i] = testObject.neighbors[i];
}
}
Test& Test::operator=(const Test& rhs) {
if (this == &rhs) {
return *this;
}
else {
name = rhs.name;
delete [] neighbors;
for (int i = 0; i < 4; i++) {
neighbors[i] = rhs.neighbors[i];
}
return *this;
}
}
你不应该删除neighbors
,因为它是一个静态数组。而是依次删除其每个元素。也仅当它们归当前对象所有时才删除它们(这在您的代码中并不明显)。
我将创建一个帮助程序私有函数destroy
并在赋值运算符和析构函数中重用它以避免代码重复。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板