template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other) {
Node<T> *temp = other.stktop;
if (other.stktop != nullptr) {
Node<T> *newnode = new Node<T>;
newnode = temp;
while (temp->next != nullptr) {
temp = temp->next;
newnode->next = temp;
}
}
}
Это мой конструктор копий.
template <typename U>
struct Node {
U data;
Node<U> *next;
};
Node<T> *stktop;
и это мой структурный узел, расположенный в закрытом разделе моего класса LinkedStack.
Я попытался следовать логике написания конструкторов копирования и придумал этот код. Но он не работает. Есть идеи, что не так?
Что-то вроде того:
template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other)
{
// Create first node
if (!other.stktop) // Use pointer to bool cast
{
stktop = new Node<T>;
// Copy data. This is the simplest copy if U support it.
stktop->data = other.stktop->data;
}
else
{
stktop = nullptr; // Very important otherwise its value is undefined
return;
}
auto pothernode = other.stktop;
auto pthisnode = stktop;
// Iterate overall the elements
while (pothernode->next)
{
pthisnode->next = new Node<T>;
pthisnode->next->data = pothernode->next->data;
pothernode = pothernode->next;
pthisnode = pthisnode->next;
}
}
Обратите внимание, что все узлы расположены в куче, поэтому не забудьте удалить их. Я предлагаю использовать std::unique_ptr
или же std::shared_ptr
вместо чистого указателя.
Некоторая возможная оптимизация:
template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other)
{
const auto& pothernode = other.stktop;
auto& pthisnode = stktop;
pthisnode = nullptr;
// Iterate overall the elements
while (pothernode)
{
pthisnode = new Node<T>;
pthisnode->data = pothernode->data;
pothernode = pothernode->next;
pthisnode = pthisnode->next;
}
}
Других решений пока нет …