复制构造函数错误"Terminate called after throwing an instance of 'int'"



任务是为Forward_list类创建一个复制构造函数,这是我尝试过的代码。但是它一直显示一个错误:

抛出'int'实例后终止调用

我一直在编辑和修改,但我似乎无法克服这个错误。

class Forward_list
{
public:
class Node
{
public:
// A node will hold data of type T
T data{};
// next will point to the next node in the list
// we initialise next to nullptr
Node* next = nullptr;

// Because we have already intialised the variables
// the default constructor doesn't need to do anything
Node(){}

// if the constructor is called with just one argument.
Node(T input_data, Node* next_node= nullptr)
{
data = input_data;
next = next_node;
}

// Destructor
~Node(){}
};

private:
// private member variables for Forward_list
unsigned size_ = 0;
Node* head_ = nullptr;

public:
Forward_list(const Forward_list<T>& other);
template <typename T>
Forward_list<T>::Forward_list(const Forward_list& other) {
head_ = nullptr;
Node *prev_node = nullptr;
for(Node *other = head_; other != nullptr; other = other->next) {
Node *new_node = new Node;
new_node->data = other->data;
new_node->next = nullptr;
if (!head_)
head_ = new_node;
else
prev_node->next = new_node;
prev_node = new_node;
}
}

此代码中没有throws和int。所以它必须在你没有展示的代码中。可能在T的构造函数中?

并不重要,因为你的复制构造函数甚至根本没有运行它的循环,因为你在循环错误的列表。当你需要用other.head_开始循环时,你正在用this->head_开始循环。

同样,转换Node的构造函数应该通过const引用接受input_data形参,并使用成员初始化列表,以避免在单独的操作中默认构造data成员,然后再赋值。

同样,Forward_list复制构造函数也可以简化。

同样,如果你还没有这样做(你没有显示代码),请确保你遵循了3/5/0规则。

试试这样写:

class Forward_list
{
public:
class Node
{
public:
T data;
Node* next;

Node(const T &input_data, Node* next_node = nullptr);
};

Forward_list() = default;
Forward_list(const Forward_list<T>& other);
Forward_list(Forward_list<T>&& other);
~Forward_list();
Forward_list& operator=(Forward_list<T> other);
...
private:
// private member variables for Forward_list
unsigned size_ = 0;
Node* head_ = nullptr;
};
template <typename T>
Forward_list<T>::Node(const T &input_data, Node* next_node)
: data(input_data), next(next_node)
{
}
template <typename T>
Forward_list<T>::Forward_list(const Forward_list& other) {
Node **new_node = &head_;
for(Node *other_node = other.head_; other_node != nullptr; other_node = other_node->next) {
*new_node = new Node(other->data);
++size_;
new_node = &((*new_node)->next);
}
}
template <typename T>
Forward_list<T>::Forward_list(Forward_list&& other) :
head_(std::exchange(other.head_, nullptr)),
size_(std::exchange(other.size_, 0))
{
}
template <typename T>
Forward_list<T>::~Forward_list() {
Node *node = head_;
while (node) {
Node *next = node->next;
delete node;
node = next;
}
}
template <typename T>
Forward_list<T>& Forward_list<T>::operator=(Forward_list other)
{
std::swap(head_, other.head_);
std::swap(size_, other.size_);
return *this;
}

相关内容

  • 没有找到相关文章