我试图了解 C++ 中的复制构造函数、运算符重载和析构函数。给定一个包含指向它自己类型的指针的类,如何编写复制构造函数或 = 运算符重载?我尝试了以下操作,但在 main.js 中声明或分配 Test 对象时,我不断遇到分段错误。谁能解释我做错了什么?
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;
}
}