从赋值运算符调用构造函数
Calling the constructor from the assignment operator
我正在重载 class Arr 的赋值运算符。这是通过使用析构函数删除旧对象(并释放分配的内存),然后使用复制构造函数(先前已重载)使调用对象成为 rhs 的副本来实现的。 this 图片显示了执行此操作的两种不同方法(只有第 50 行和第 57 行不同)。为什么第二种解决方案有效,而第一种无效?
错误信息是"type name is not allowed"
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);
}
我知道可以使用复制和交换,但仍然:这里出了什么问题?
好吧,在 GCC 中,两者都是不允许的。我的猜测是,如果你的编译器允许一个而不允许另一个,那么这是为了避免歧义。
当您编写 this->Arr()
时,编译器无法知道您要调用构造函数,而不仅仅是实例化一个新对象。
当你写this->Arr::Arr()
时,编译器就知道你调用了classArr
的static函数Arr()
].
我正在重载 class Arr 的赋值运算符。这是通过使用析构函数删除旧对象(并释放分配的内存),然后使用复制构造函数(先前已重载)使调用对象成为 rhs 的副本来实现的。 this 图片显示了执行此操作的两种不同方法(只有第 50 行和第 57 行不同)。为什么第二种解决方案有效,而第一种无效?
错误信息是"type name is not allowed"
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);
}
我知道可以使用复制和交换,但仍然:这里出了什么问题?
好吧,在 GCC 中,两者都是不允许的。我的猜测是,如果你的编译器允许一个而不允许另一个,那么这是为了避免歧义。
当您编写 this->Arr()
时,编译器无法知道您要调用构造函数,而不仅仅是实例化一个新对象。
当你写this->Arr::Arr()
时,编译器就知道你调用了classArr
的static函数Arr()
].