复制构造函数,重载赋值运算符和deepCopy

时间:2016-04-04 01:37:11

标签: c++ templates linked-list

我正在尝试为Stack的链接列表实现创建一个类模板。现在我已经得到了推,弹,窥视和测试析构函数。但我想知道如何在我的代码中添加复制构造函数,重载赋值运算符和deepCopy。这是我到目前为止所得到的:

//  Lab3.cpp
//
//  Created by IvanChak on 4/3/16.
//  Copyright © 2016 Space. All rights reserved.

#include <iostream>
using namespace std;

template<class T>
struct Node {
    T item;
    Node* next = NULL;
    Node(T t = {}, Node* link = nullptr) :item{t}, next{link} { }
    ~Node() { delete next; }
};

template<class T>
class Stack {
public:
    bool empty() const { return n == 0; }
    void push(const T&);
    T pop();
    T peek();
    ~Stack();

private:
    Node<T>* top = NULL;
    size_t n;
};

template <class T>
class A
{
public:
    A(const A &){}
    A & operator=(const A& a){return *this;}
};

template<class T>
Stack<T>::~Stack() {
    cout<<"Destructor, deallocate..."<<endl;
}

template<class T>
void Stack<T>::push(const T& t) {
    Node<T>* previous{top};
    top = new Node<T>{t,previous};
    ++n;
}

template<class T>
T Stack<T>::pop() {
    if (empty()) {
        cout << "Empty" << endl;
    }
    Node<T>* oldnode = top;
    T t = top->item;
    top = top->next;
    --n;
    delete oldnode;
    return t;
}

template<class T>
T Stack<T>::peek() {
    if (empty()) {
        cout << "Empty" << endl;
    }
    return top->item;
}

int main(int argc, const char * argv[]) {
    Stack<string> x{};
    x.push("Hello");
    x.push("Second");
    x.push("Bye");
    cout << x.peek() << endl;
    x.pop();
    cout << x.peek() << endl;
}

1 个答案:

答案 0 :(得分:1)

我不知道你是否还需要答案,但是如果你这样做,你会想要这样的东西给你复制构造函数和你的赋值操作符:

template<class T>
Stack<T>::Stack(const Stack<T>& rhs)
{
    if (rhs.top)
    {
        this->top = new Node<T>(rhs.top->item);

        Node<T>* rhsNode = rhs.top; // This pointer is used for iterating through the "rhs" argument.
        Node<T>* currentNode = this->top; // This pointer is used for iterating through "this".

        n = 1;

        while (rhsNode->next) // Loop untill the end of the stack has been reached.
        {
            ++n;

            currentNode->next = new Node<T>(rhsNode->next->item);

            currentNode = currentNode->next;
            rhsNode = rhsNode->next;
        }
    }
    else // "rhs" is empty
    {
        n = 0;

        this->top = nullptr;
    }
}

注意:我在&#34;深层副本中编写了此代码&#34;时尚。我无法想到任何情况下做一个&#34;浅拷贝&#34;在这种类型的数据结构上;事实上,我认为这样做是一个非常糟糕的主意。我不会自动假设您正在计划让您的复制构造函数做一个浅层复制&#34;在你的堆栈上,但因为你命名了复制构造函数和关于&#34;深度复制&#34;另外,我认为你完全有可能。

我测试了这段代码,但它确实有效。

相关问题