gpt4 book ai didi

C++14 不能调用从唯一指针继承的类的复制构造函数或运算符=

转载 作者:行者123 更新时间:2023-11-28 01:41:09 25 4
gpt4 key购买 nike

我在调用构造函数/运算符时遇到问题。我有一个 Tree 类,它是一个指向节点的唯一指针。这是我实现移动和复制构造函数/运算符的代码。

template <class Key, class Data>
class Node;

template <class Key, class Data>
class Tree : public unique_ptr<Node<Key, Data>>
{
using unique_ptr<Node<Key, Data>>::unique_ptr;
public:

/*Default empty constructor*/
Tree(){
this->reset();
}

/*Default constructor*/
Tree(const Key& key, const Data& data) : unique_ptr<Node<Key, Data>>(make_unique<Node<Key, Data>>(key, data)) {
}

/*Copy constructor*/
Tree(const unique_ptr<Node<Key, Data>>& tree) : unique_ptr<Node<Key, Data>>(nullptr){
if(tree){
this->reset(new Node<Key, Data>(*tree));
}
}

/*Move constructor: roep de move constructor van unique_ptr op*/
Tree(unique_ptr<Node<Key, Data>>&& tree) : unique_ptr<Node<Key, Data >>(move(tree)) {
}

/*Copy operator*/
Tree<Key, Data>& operator=(const unique_ptr<Node<Key, Data>>& tree) {
if (this != &tree) {
this->reset(make_unique(Tree<Key, Data>(*tree)));
if ((*this)->left != nullptr) {
(*this)->left = tree->left;
}
if ((*this)->right != nullptr) {
(*this)->right = tree->right;
}
}
return *this;
}

/*Move operator*/
Tree<Key, Data>& operator=(unique_ptr<Node<Key, Data >>&& tree) {
if (this != &tree) {
*this = unique_ptr<Key, Data>::operator=(std::move(tree));
}
return *this;
}}

当我尝试使用构造函数或 operator= 将树 a 复制到树 b 时,我收到一条错误消息,告诉我运算符已被隐式删除。我知道当你实现一个移动/复制构造函数/操作符时,默认的就不能再使用了,你也必须实现所有其他的。但从我的角度来看,我实现了所有这些。

代码示例

Tree<int, char> tree;
Tree<int, char> copy;
copy = tree;

错误:无法分配“树”类型的对象,因为它的复制赋值运算符被隐式删除

最佳答案

您的“移动构造函数”和“复制赋值运算符”没有正确的签名。它们应该是 Tree(Tree&&)Tree& operator=(const Tree&)

当您执行 copy = tree; 时,不会使用您的任何函数,但会选择编译器生成的默认赋值运算符。而这恰好被删除了 (= delete;) 因为基类的复制赋值被删除了。

关于C++14 不能调用从唯一指针继承的类的复制构造函数或运算符=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47110804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com