在C ++中正确使用构造函数

时间:2015-02-18 22:38:15

标签: c++ constructor linked-list

我有一个简单的赋值函数如下:

LinkedList& LinkedList::operator=(const LinkedList &l) {
    // handle self assignment
    if (this == &l) {
        return *this;
    }

    // free old elements of the list before the new elements from l are assigned
    ~*this();

    // build the list as a deep copy of l (copy constructor handles empty case)
    this(l);

    return *this;
}

每当我运行程序时,我都会收到error: ‘this’ cannot be used as a function响应。我该如何在实际环境中使用构造函数?非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

手动调用构造函数或析构函数几乎总是一个非常糟糕的主意。它们不是为它设计的。

您应该创建单独的功能来清除和复制列表。构造函数和析构函数可以使用这些方法。

答案 1 :(得分:3)

您尝试的正确语法是:

this->~LinkedList();  
new(this) LinkedList(l);

您已经清楚地意识到避免代码重复是件好事,但是首选的方法是使用copy and swap idiom来编写赋值运算符。