C++复制构造函数和 = 运算符重载

C++ Copy Constructor and = operator overloading

本文关键字:运算符 重载 复制 构造函数 C++      更新时间:2023-10-16

我正在尝试在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并在赋值运算符和析构函数中重用它以避免代码重复。