简体   繁体   English

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

[英]C++ Copy Constructor and = operator overloading

I am trying to get my head around copy constructors, operator overloading and destructors in C++. 我正在努力弄清C ++中的复制构造函数,运算符重载和析构函数。 Given a class which contains a pointer to it's own type, how would one write the copy constructors or = operator overload? 给定一个包含指向其自身类型的指针的类,将如何编写副本构造函数或=运算符重载? I have attempted the following, but I keep getting segmentation faults when declaring or assigning Test objects in main. 我尝试了以下操作,但是在main中声明或分配Test对象时,我始终遇到分段错误。 Could anyone explain what I am doing incorrectly? 谁能解释我做错了什么?

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;
    }
}

You should not delete neighbors as it is a static array. 您不应删除neighbors因为它是静态数组。 Instead delete each of its elements in turn. 而是依次删除其每个元素。 Also only delete them if they are owned by the current object(this is not apparent from your code). 如果它们是当前对象所拥有的,也仅将它们删除(这在您的代码中并不明显)。

I would create a helper private function destroy and re-use it in the assignment operator and in the destructor to avoid code duplication. 我将创建一个帮助器私有函数, destroy它并在赋值运算符和析构函数中重新使用它,以避免代码重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM