复制使用列表类的堆栈类的构造函数

时间:2014-10-13 04:25:00

标签: c++ class templates

如何为具有私有成员的模板类调用复制构造函数,该私有成员也是另一个模板对象

我正在构建一个堆栈类,它使用list类来构建堆栈。 list类有一个拷贝构造函数, 所以我想复制stack1 = stack2 如何在堆栈复制构造函数

的复制构造函数中调用它

最后一个代码是堆栈类的复制构造函数,我正在尝试复制私有成员list_3 myData

当我做myData = src.myData时; //它复制相同的地址,但不提供新对象

template <class ItemType>
            class List_3
            {

            public:


                typedef size_t size_type;

                List_3();

                List_3(const List_3 & src);

                ~List_3();

                void insert(const ItemType & item);

                void remove(); 

                void reset();

                bool advance();

                bool isEmpty() const;

                bool atEOL() const;

                bool isFull() const;

                ItemType getCurrent() const;


            private:

                struct Node {
                    ItemType value;
                    Node* next;
                    Node* previous;
                };

                Node* head;
                Node* tail;
                Node* cursor;

            };

    //Copy Constructor for List class**
    template<class ItemType>
    List_3<ItemType>::List_3(const List_3<ItemType> & src)
    {
        //Copy constructor
        head = NULL;
        tail = NULL;
        cursor = NULL;
        Node *tempCursor = new Node;
        tempCursor = src.head; // copying the original list from head to tail
        if (!src.isEmpty()) {   //if the src list is not empty start copy process
            while (tempCursor != NULL)
            {
                insert(tempCursor->value);
                cursor = NULL;
                tempCursor = tempCursor->next;  //Move to the next item in the list use previous if copying from tail
            }
            reset();                            //Reset the cursor
        }



    }


    **//============================================================================**

        template<class ItemType>
            class Stack_3 {
            public:

                typedef int size_type;

                Stack_3();

                //Copy constructor
                Stack_3(const Stack_3 & src);

                void makeEmpty();

                bool isEmpty() const;

                bool isFull() const;

                void push(const ItemType &);

                ItemType pop();

            private:
                List_3<ItemType> myData;

            };

    **//Copy Constructor for Stack Class**
    template<class ItemType>
    Stack_3358<ItemType>::Stack_3358(const Stack_3358<ItemType> & src)
    {

        myData = src.myData;

    }

2 个答案:

答案 0 :(得分:0)

How do you call a copy constructor?

你不打电话给构造函数。当您创建相应类的对象

时,构造函数会自动运行

答案 1 :(得分:0)

您需要初始化列表才能实现此目标

Stack_3358<ItemType>::Stack_3358(const Stack_3358<ItemType> & src) 
                     : myData(src.myData) // this calls List_3 copy constructor
{

}

myData = src.myData;将使用复制分配的运算符,该运算符将使用相同的地址,除非复制赋值运算符过载。

相关问题