从赋值运算符调用构造函数

时间:2017-05-08 15:56:21

标签: c++ constructor operator-overloading assignment-operator

我正在为类Arr重载赋值运算符。这是通过使用析构函数删除旧对象(并释放已分配的内存),然后使用copy-constructor(先前已重载)来使调用对象成为rhs的副本来实现的。 this 图片显示了两种不同的方法(仅50行和57行不同)。为什么第二种解决方案有效,但不是第一种?

错误消息是“不允许输入类型名称”

Arr& Arr::operator=(const Arr& rhs) {
    this->~Arr();
    this->Arr(rhs); // I get an error here: type name is not allowed
    return (*this);
}


Arr& Arr::operator=(const Arr& rhs) {
    this->~Arr();
    this->Arr::Arr(rhs);
    return (*this);
}

我知道可以使用copy-and-swap,但仍然:这里出了什么问题?

1 个答案:

答案 0 :(得分:-1)

嗯,在海湾合作委员会中都不允许。我的猜测是,如果你的编译器允许一个而不允许另一个,那么就是避免消歧。

当你编写this->Arr()时,编译器无法知道你打算调用构造函数,而不是只是实例化一个新对象。

当您编写this->Arr::Arr()时,编译器知道您调用类Arr()静态函数Arr